ggfm.models.HeteroLlamaForCausalLM

class ggfm.models.HeteroLlamaForCausalLM(config)[source]

HeteroLLaMA model for causal language modeling with heterogeneous graphs.

Extends LlamaForCausalLM to support language modeling conditioned on heterogeneous graph structures.

Parameters:

config (HeteroLlamaConfig) – Model configuration

config_class

alias of HeteroLlamaConfig

forward(input_ids: LongTensor | None = None, attention_mask: Tensor | None = None, past_key_values: List[FloatTensor] | None = None, inputs_embeds: FloatTensor | None = None, labels: LongTensor | None = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, graph_data: Data | None = None, return_dict: bool | None = None, hetero_key_order: List[List[str]] | None = None) Tuple | CausalLMOutputWithPast[source]

The [LlamaForCausalLM] forward method, overrides the __call__ special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the [Module] instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

</Tip>

Parameters:
  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) –

    Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.

    Indices can be obtained using [AutoTokenizer]. See [PreTrainedTokenizer.encode] and [PreTrainedTokenizer.__call__] for details.

    [What are input IDs?](../glossary#input-ids)

  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) –

    Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

    [What are attention masks?](../glossary#attention-mask)

    Indices can be obtained using [AutoTokenizer]. See [PreTrainedTokenizer.encode] and [PreTrainedTokenizer.__call__] for details.

    If past_key_values is used, optionally only the last input_ids have to be input (see past_key_values).

    If you want to change padding behavior, you should read [modeling_opt._prepare_decoder_attention_mask] and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.

    • 1 indicates the head is not masked,

    • 0 indicates the head is masked.

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) –

    Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1].

    [What are position IDs?](../glossary#position-ids)

  • past_key_values (Cache or tuple(tuple(torch.FloatTensor)), optional) –

    Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Two formats are allowed: - a [~cache_utils.Cache] instance, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache); - Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)). This is also known as the legacy cache format.

    The model will output the same cache format that is fed as input. If no past_key_values are passed, the legacy cache format will be returned.

    If past_key_values are used, the user can optionally input only the last input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, 1) instead of all input_ids of shape (batch_size, sequence_length).

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) – Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

  • use_cache (bool, optional) – If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

  • output_attentions (bool, optional) – Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) – Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • return_dict (bool, optional) – Whether or not to return a [~utils.ModelOutput] instead of a plain tuple.

  • cache_position (torch.LongTensor of shape (sequence_length), optional) – Indices depicting the position of the input sequence tokens in the sequence. Contrarily to position_ids, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.

  • Args

    labels (torch.LongTensor of shape (batch_size, sequence_length), optional):

    Labels for computing the masked language modeling loss. Indices should either be in [0, …, config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, …, config.vocab_size].

    num_logits_to_keep (int, optional):

    Calculate logits for the last num_logits_to_keep tokens. If 0, calculate logits for all input_ids (special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size.

  • Returns

    [transformers.modeling_outputs.CausalLMOutputWithPast] or tuple(torch.FloatTensor): A [transformers.modeling_outputs.CausalLMOutputWithPast] or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration ([LlamaConfig]) and inputs.

    • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) – Language modeling loss (for next-token prediction).

    • logits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) – Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

    • past_key_values (tuple(tuple(torch.FloatTensor)), optional, returned when use_cache=True is passed or when config.use_cache=True) – Tuple of tuple(torch.FloatTensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head))

      Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding.

    • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) – Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

      Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.

    • attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) – Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

      Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.

  • Example

  • ```python

  • AutoTokenizer (>>> from transformers import) –

  • LlamaForCausalLM

  • LlamaForCausalLM.from_pretrained (>>> model =) –

  • AutoTokenizer.from_pretrained (>>> tokenizer =) –

  • "Hey (>>> prompt =) –

  • me?" (are you conscious? Can you talk to) –

  • tokenizer (>>> inputs =) –

  • Generate (>>> #) –

  • model.generate (>>> generate_ids =) –

  • tokenizer.batch_decode (>>>) –

  • "Hey

  • conscious (are you conscious? Can you talk to me?nI'm not) –

  • you." (but I can talk to) –

  • ```

get_graph_tower()[source]

Get the heterogeneous graph processing component.

get_model()[source]

Get the underlying HeteroLlamaModel.

initialize_graph_tokenizer(use_graph_start_end, tokenizer, device, tune_graph_mlp_adapter=False, pretrain_graph_mlp_adapter=None)[source]
prepare_inputs_for_generation(input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs)[source]

Prepare the model inputs for generation. In includes operations like computing the 4D attention mask or slicing inputs given the existing cache.

See the forward pass in the model documentation for expected arguments (different models might have different requirements for e.g. past_key_values). This function should work as is for most LLMs.

training: bool