llama3

Llama3 standalone implementation inspired from https://github.com/rasbt/LLMs-from-scratch/blob/main/ch05/07_gpt_to_llama/standalone-llama32.ipynb Explanations on grouped query attention: https://www.ibm.com/think/topics/grouped-query-attention.

class mfai.pytorch.models.llms.llama3.GroupedQueryAttention(d_in, d_out, num_heads, num_kv_groups)[source]

Bases: Module

Parameters:
  • d_in (int)

  • d_out (int)

  • num_heads (int)

  • num_kv_groups (int)

forward(x, mask, cos, sin, start_pos=0, cache=None)[source]

Performs the forward pass of grouped query attention.

This implements multi-head attention with grouped query heads, where multiple query heads share the same key-value pairs. This reduces memory usage and computation compared to standard multi-head attention while maintaining performance.

Parameters:
  • x (Tensor) – Input tensor of shape (batch_size, num_tokens, d_in)

  • mask (Tensor) – Attention mask of shape (batch_size, 1, num_tokens, num_tokens) Used to prevent attention to future tokens in causal masking

  • cos (Tensor) – Cosine values for RoPE positional encoding

  • sin (Tensor) – Sine values for RoPE positional encoding

  • start_pos (int, optional) – Starting position for RoPE positional encoding. Defaults to 0.

  • cache (tuple[Tensor, Tensor], optional) – Cached key-value tensors from previous iterations. Defaults to None.

Returns:

A tuple containing:
  • context_vec (Tensor): Output tensor of shape (batch_size, num_tokens, d_out)

  • next_cache (tuple[Tensor, Tensor]): Updated cache tensors for next iteration (keys_cache, values_cache).

Return type:

tuple[Tensor, tuple[Tensor, Tensor]]

class mfai.pytorch.models.llms.llama3.Llama3(settings, vocab_size=32000)[source]

Bases: Module

Parameters:
embed_tokens(tok_ids)[source]
Return type:

Tensor

Parameters:

tok_ids (Tensor)

forward(tok_ids, use_cache=False)[source]

Performs the forward pass of the LLama3 model.

Parameters:
  • tok_ids (Tensor) – Tensor of token IDs input with shape (batch_size, sequence_length).

  • use_cache (bool, optional) – If True, uses attention caching for computational optimization. Defaults to False.

Returns:

Model output tensor with shape (batch_size, sequence_length, hidden_size) or

(batch_size, context_length, hidden_size) depending on model dimensions.

Return type:

Tensor

Note

The KV cache implementation is largely inspired by S. Rashka. See https://github.com/rasbt/LLMs-from-scratch/blob/main/pkg/llms_from_scratch/llama3.py for more details.

forward_vectors(embeddings, first_embedding=None, use_cache=False)[source]

Process a batch of embeddings through the model. If first_embedding is supplied the first tokens of each blocks are replaced by the corresponding embeddings. Useful for multimodal models with injection of vision data embeddings at each stage.

Return type:

Tensor

Parameters:
model_type = 4
reset_kv_cache()[source]

Clear the Key-Value cache used for incremental decoding.

This method must be called between processing independent sequences to prevent cross-sequence contamination in autoregressive generation. After calling this method, the cache will be reset to None and ready for a new sequence.

Return type:

None

settings_kls

alias of Llama3Settings

class mfai.pytorch.models.llms.llama3.Llama3Settings(emb_dim=256, context_length=512, n_heads=8, n_layers=8, hidden_dim=768, num_kv_groups=2, rope_base=500000.0)[source]

Bases: object

Parameters:
  • emb_dim (int)

  • context_length (int)

  • n_heads (int)

  • n_layers (int)

  • hidden_dim (int)

  • num_kv_groups (int)

  • rope_base (float)

context_length: int
emb_dim: int
classmethod from_dict(kvs, *, infer_missing=False)
Return type:

TypeVar(A, bound= DataClassJsonMixin)

Parameters:

kvs (dict | list | str | int | float | bool | None)

classmethod from_json(s, *, parse_float=None, parse_int=None, parse_constant=None, infer_missing=False, **kw)
Return type:

TypeVar(A, bound= DataClassJsonMixin)

Parameters:

s (str | bytes | bytearray)

hidden_dim: int
n_heads: int
n_layers: int
num_kv_groups: int
rope_base: float
classmethod schema(*, infer_missing=False, only=None, exclude=(), many=False, context=None, load_only=(), dump_only=(), partial=False, unknown=None)
Return type:

SchemaF[TypeVar(A, bound= DataClassJsonMixin)]

Parameters:
to_dict(encode_json=False)
Return type:

Dict[str, Union[dict, list, str, int, float, bool, None]]

to_json(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, default=None, sort_keys=False, **kw)
Return type:

str

Parameters:
class mfai.pytorch.models.llms.llama3.TransformerBlock(emb_dim, hidden_dim, num_heads, num_kv_groups, dtype=None)[source]

Bases: Module

Parameters:
  • emb_dim (int)

  • hidden_dim (int)

  • num_heads (int)

  • num_kv_groups (int)

  • dtype (dtype | None)

forward(x, mask, cos, sin, start_pos, cache)[source]

Define the computation performed at every call.

Should be overridden by all subclasses. :rtype: tuple[Tensor, tuple[Tensor, Tensor]]

Note

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 registered hooks while the latter silently ignores them.

Parameters:
Return type:

tuple[Tensor, tuple[Tensor, Tensor]]

mfai.pytorch.models.llms.llama3.apply_rope(x, cos, sin, offset=0)[source]
Return type:

Tensor

Parameters:
mfai.pytorch.models.llms.llama3.compute_rope_params(head_dim, theta_base=10000.0, context_length=4096)[source]
Return type:

tuple[Tensor, Tensor]

Parameters:
  • head_dim (int)

  • theta_base (float)

  • context_length (int)