qwen3_5

Pytorch implementation of Qwen 3.5. It is widely inspired by Sebastian Raschka’s book and work https://github.com/rasbt/LLMs-from-scratch/blob/main/ch05/16_qwen3.5.

Qwen3.5 helper blocks copied from Hugging Face Transformers Source file: https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_5/modeling_qwen3_5.py

class mfai.pytorch.models.llms.qwen3_5.FeedForward(settings)[source]

Bases: Module

Parameters:

settings (Qwen3_5Settings)

forward(x)[source]

Define the computation performed at every call.

Should be overridden by all subclasses. :rtype: 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:

x (Tensor)

Return type:

Tensor

class mfai.pytorch.models.llms.qwen3_5.GroupedQueryAttention(d_in, num_heads, num_kv_groups, head_dim=None, qk_norm=False, dtype=None)[source]

Bases: Module

Parameters:
  • d_in (int)

  • num_heads (int)

  • num_kv_groups (int)

  • head_dim (int | None)

  • qk_norm (bool)

  • dtype (dtype | None)

forward(x, mask, cos, sin, start_pos=0, cache=None)[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]]

class mfai.pytorch.models.llms.qwen3_5.KVCache(n_layers)[source]

Bases: object

Parameters:

n_layers (int)

get(layer_idx)[source]
Return type:

tuple[Tensor, Tensor] | None

Parameters:

layer_idx (int)

get_all()[source]
Return type:

list[None | tuple[Tensor, Tensor]]

reset()[source]
Return type:

None

update(layer_idx, value)[source]
Return type:

None

Parameters:
class mfai.pytorch.models.llms.qwen3_5.Qwen3_5(settings)[source]

Bases: Module

Parameters:

settings (Qwen3_5Settings)

compute_memory_size(input_dtype=torch.float32)[source]
Return type:

float

Parameters:

input_dtype (dtype)

create_mask(cur_len, device, pos_start=0, pos_end=None)[source]
Return type:

Tensor

Parameters:
download_weights_from_hf(model_dir)[source]
Return type:

None

Parameters:

model_dir (Path)

forward(in_idx, cache=None)[source]

Define the computation performed at every call.

Should be overridden by all subclasses. :rtype: 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:

Tensor

generate_output_stream(token_ids, max_new_tokens, eos_token_id=None)[source]
Return type:

Iterator[Tensor]

Parameters:
  • token_ids (Tensor)

  • max_new_tokens (int)

  • eos_token_id (int | None)

generate_text(prompt, tokenizer, max_new_tokens)[source]
Return type:

str

Parameters:
  • prompt (str)

  • max_new_tokens (int)

load_weights_from_dict(params)[source]
Return type:

None

Parameters:

params (dict)

model_type = 4
reset_kv_cache()[source]
Return type:

None

settings_kls

alias of Qwen3_5Settings

class mfai.pytorch.models.llms.qwen3_5.Qwen3_5GatedDeltaNet(settings, layer_idx)[source]

Bases: Module

Parameters:
forward(hidden_states, cache_params=None, cache_position=None, attention_mask=None)[source]

Define the computation performed at every call.

Should be overridden by all subclasses. :rtype: 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:

Tensor

class mfai.pytorch.models.llms.qwen3_5.Qwen3_5LinearAttentionCache(n_layers)[source]

Bases: object

Parameters:

n_layers (int)

reset()[source]
Return type:

None

class mfai.pytorch.models.llms.qwen3_5.Qwen3_5RMSNormGated(hidden_size, eps=1e-06)[source]

Bases: Module

Parameters:
forward(hidden_states, gate=None)[source]

Define the computation performed at every call.

Should be overridden by all subclasses. :rtype: 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:

Tensor

class mfai.pytorch.models.llms.qwen3_5.Qwen3_5Settings(vocab_size=248320, context_length=262144, emb_dim=1024, n_heads=8, n_layers=24, hidden_dim=3584, head_dim=256, qk_norm=True, n_kv_groups=2, rope_base=10000000, partial_rotary_factor=0.25, rms_norm_eps=1e-06, linear_conv_kernel_dim=4, linear_key_head_dim=128, linear_value_head_dim=128, linear_num_key_heads=16, linear_num_value_heads=16, dtype=torch.bfloat16, layer_types=('linear_attention', 'linear_attention', 'linear_attention', 'full_attention', 'linear_attention', 'linear_attention', 'linear_attention', 'full_attention', 'linear_attention', 'linear_attention', 'linear_attention', 'full_attention', 'linear_attention', 'linear_attention', 'linear_attention', 'full_attention', 'linear_attention', 'linear_attention', 'linear_attention', 'full_attention', 'linear_attention', 'linear_attention', 'linear_attention', 'full_attention'), hidden_activation='silu')[source]

Bases: object

Qwen3.5-0.8B text configuration

Parameters:
  • vocab_size (int)

  • context_length (int)

  • emb_dim (int)

  • n_heads (int)

  • n_layers (int)

  • hidden_dim (int)

  • head_dim (int)

  • qk_norm (bool)

  • n_kv_groups (int)

  • rope_base (int)

  • partial_rotary_factor (float)

  • rms_norm_eps (float)

  • linear_conv_kernel_dim (int)

  • linear_key_head_dim (int)

  • linear_value_head_dim (int)

  • linear_num_key_heads (int)

  • linear_num_value_heads (int)

  • dtype (dtype)

  • layer_types (tuple[str, ...])

  • hidden_activation (str)

context_length: int
dtype: dtype
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)

head_dim: int
hidden_activation: str
hidden_dim: int
layer_types: tuple[str, ...]
linear_conv_kernel_dim: int
linear_key_head_dim: int
linear_num_key_heads: int
linear_num_value_heads: int
linear_value_head_dim: int
n_heads: int
n_kv_groups: int
n_layers: int
partial_rotary_factor: float
qk_norm: bool
rms_norm_eps: float
rope_base: int
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:
vocab_size: int
class mfai.pytorch.models.llms.qwen3_5.RMSNorm(emb_dim, eps=1e-06)[source]

Bases: Module

Parameters:
forward(x)[source]

Define the computation performed at every call.

Should be overridden by all subclasses. :rtype: 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:

x (Tensor)

Return type:

Tensor

class mfai.pytorch.models.llms.qwen3_5.TransformerBlock(settings, layer_type, layer_idx)[source]

Bases: Module

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

Define the computation performed at every call.

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

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] | None]

mfai.pytorch.models.llms.qwen3_5.apply_mask_to_padding_states(hidden_states, attention_mask)[source]

Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66

Return type:

Tensor

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

Tensor

Parameters:
mfai.pytorch.models.llms.qwen3_5.compute_rope_params(head_dim, theta_base=10000, context_length=4096, partial_rotary_factor=1.0, dtype=torch.float32)[source]
Return type:

tuple[Tensor, Tensor]

Parameters:
  • head_dim (int)

  • theta_base (int)

  • context_length (int)

  • partial_rotary_factor (float)

  • dtype (dtype)

mfai.pytorch.models.llms.qwen3_5.l2norm(x, dim=-1, eps=1e-06)[source]

This function is intended to align with the l2norm implementation in the FLA library.

Return type:

Tensor

Parameters:
mfai.pytorch.models.llms.qwen3_5.torch_causal_conv1d_update(hidden_states, conv_state, weight, bias=None)[source]
Return type:

Tensor

Parameters:
mfai.pytorch.models.llms.qwen3_5.torch_chunk_gated_delta_rule(query, key, value, gate, beta, chunk_size=64, initial_state=None, output_final_state=False, use_qk_l2norm_in_kernel=False)[source]
Return type:

tuple[Tensor, Tensor | None]

Parameters:
mfai.pytorch.models.llms.qwen3_5.torch_recurrent_gated_delta_rule(query, key, value, g, beta, initial_state, output_final_state, use_qk_l2norm_in_kernel=False)[source]
Return type:

tuple[Tensor, Tensor | None]

Parameters: