Skip to navigation

nemo_automodel.components.models.hy_v4_flash.model

View as MarkdownOpen in Claude

Hy4-flash decoder stack for AutoModel training (text backbone; the vision tower is in vision.py).

Forward contract (transformers reference HYV4FlashTextModel): tokens are embedded and replicated into hc_mult residual streams [batch, sequence, hc_mult, hidden]. Each block optionally applies Engram to the streams, then attn_hc -> input_layernorm -> gated MLA -> post_self_attn_layernorm -> scatter, then ffn_hc -> post_attention_layernorm -> dense MLP / latent MoE -> post_mlp_layernorm -> scatter. hc_head collapses the streams before the final RMSNorm and the fp32 lm_head.

Batch rows and packed documents are flattened into one token axis for attention and never attend to each other. Context parallelism shards the packed row and gathers keys per layer. Pipeline parallelism is not supported.

Module Contents

Classes

NameDescription
HYV4FlashBatchFlattened-token view of one forward pass, shared by all layers.
HYV4FlashBlockOne sandwich-normed, hyper-connected decoder layer.
HYV4FlashCPInputsModel-owned context-parallel inputs handed to the training recipe.
HYV4FlashForCausalLMHy4-flash: the decoder stack, the vision tower for image-text inputs, and an fp32 lm_head.
HYV4FlashModelEmbeddings, hyper-connected blocks and the output collapse.

Functions

NameDescription
build_moe_configMoE settings of the latent-space sigmoid router (all routed experts run at routed_expert_hidden_size).
compute_mrope_position_idsM-RoPE positions of mixed text / image rows (the reference get_rope_index).
vision_position_ids3-D positions of one image/video: every merged row has w + 1 tokens (the last is the newline).

Data

HYV4FlashForConditionalGeneration

ModelClass

API

class nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashBatch(
ngram_tokens: torch.Tensor | None,
engram_mask: torch.Tensor | None,
padding_mask: torch.Tensor | None
)
Dataclass

Flattened-token view of one forward pass, shared by all layers.

engram_mask
Tensor | None

Bool tensor [batch, sequence] or None.

layout
HYV4FlashDocLayout

Document boundaries over the flattened batch * sequence token axis.

ngram_tokens
Tensor | None

Integer tensor [batch, sequence, max_ngram_size] or None without Engram layers.

padding_mask
Tensor | None

Bool tensor [batch, sequence], True at padding, or None.

ropes
dict[str, HYV4FlashRope]

Rotary tables per attention type over the flattened token axis.

class nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashBlock(
layer_idx: int,
engram_process_group: torch.distributed.ProcessGroup | None = None
)

Bases: Module

One sandwich-normed, hyper-connected decoder layer.

attention_type
= config.attention_types[layer_idx]
attn_hc
= HYV4FlashHyperConnection(config)
engram_layer
ffn_hc
= HYV4FlashHyperConnection(config)
has_moe
= config.mlp_layer_types[layer_idx] == 'sparse'
input_layernorm
= HYV4FlashRMSNorm(hidden, eps, dtype)
mlp
= MoE(moe_config, backend)
post_attention_layernorm
= HYV4FlashRMSNorm(hidden, eps, dtype)
post_mlp_layernorm
= HYV4FlashRMSNorm(hidden, eps, dtype)
post_self_attn_layernorm
= HYV4FlashRMSNorm(hidden, eps, dtype)
self_attn
= HYV4FlashAttention(config, layer_idx, backend)
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashBlock.forward(
streams: torch.Tensor,
) -> torch.Tensor

Run the layer on streams [batch, sequence, hc_mult, hidden]; the result has the same shape.

class nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashCPInputs

Bases: typing.TypedDict

Model-owned context-parallel inputs handed to the training recipe.

cp_sharder
ContextParallelSharder
class nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM(
engram_process_group: torch.distributed.ProcessGroup | None = None,
logits_dtype: torch.dtype | None = torch.float32
)

Bases: HFCheckpointingMixin, PreTrainedModel, MoEFSDPSyncMixin

Hy4-flash: the decoder stack, the vision tower for image-text inputs, and an fp32 lm_head.

_fsdp_shard_across_blocks
_keep_in_fp32_modules_strict
_owns_cp_attention
bool = True
_packed_cp_attn_backends
= ('cudnn', 'sdpa')
backend
base_model_prefix
= 'model'
cp_mesh
DeviceMesh | None = None
image_token_id
= config.image_token_id
lm_head
model
spatial_merge_size
= vision.spatial_merge_size
state_dict_adapter
tie_word_embeddings_support
TieSupport = TieSupport.UNTIED_ONLY
vit
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM._embed(
input_ids: torch.Tensor,
pixel_values: torch.Tensor | None,
image_grid_thw: torch.Tensor | None
) -> torch.Tensor

Token embeddings [batch, sequence, hidden] with image features scattered into the image pad positions.

pixel_values has shape [patches, channels * patch_size * patch_size] and image_grid_thw [images, 3].

nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM._nemo_prepare_model_owned_dtensors(
fsdp_mesh: torch.distributed.device_mesh.DeviceMesh
) -> set[torch.nn.Parameter]

Register the row-owner-sharded Engram tables as DTensors before FSDP records its ignored parameters.

Parameters:

fsdp_mesh
DeviceMesh

One-dimensional shard mesh whose ranks and order equal the Engram owner group.

Returns: set[nn.Parameter]

The table parameters (global shape [padded_rows, head_dim], Shard(0)) that FSDP must not own.

nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM.forward(
input_ids: torch.Tensor,
position_ids: torch.Tensor | None = None,
attention_mask: torch.Tensor | None = None,
padding_mask: torch.Tensor | None = None,
packed_seq_ids: torch.Tensor | None = None,
labels: torch.Tensor | None = None,
loss_mask: torch.Tensor | None = None,
logits_to_keep: int | torch.Tensor = 0,
output_hidden_states: bool = False,
pixel_values: torch.Tensor | None = None,
image_grid_thw: torch.Tensor | None = None,
mm_token_type_ids: torch.Tensor | None = None,
cp_group: torch.distributed.ProcessGroup | None = None,
seq_lens: torch.Tensor | None = None,
seq_lens_padded: torch.Tensor | None = None,
qkv_format: str | None = None
) -> transformers.modeling_outputs.CausalLMOutputWithPast

Compute logits (and an optional mean token loss).

Parameters:

input_ids
torch.Tensor

Integer tensor of shape [batch, sequence].

position_ids
torch.Tensor | NoneDefaults to None

Optional integer tensor of shape [batch, sequence] or [3, batch, sequence].

attention_mask
torch.Tensor | NoneDefaults to None

Optional tensor of shape [batch, sequence], 1 for real tokens.

padding_mask
torch.Tensor | NoneDefaults to None

Optional bool tensor of shape [batch, sequence], True at padding (used if no attention_mask).

packed_seq_ids
torch.Tensor | NoneDefaults to None

Optional integer tensor of shape [batch, sequence] with packed-document ids.

labels
torch.Tensor | NoneDefaults to None

Optional integer tensor of shape [batch, sequence], -100 ignored. With seq_lens the first token of every document is not supervised.

loss_mask
torch.Tensor | NoneDefaults to None

Consumed by the recipe loss; accepted so the standard batch reaches the model.

logits_to_keep
int | torch.TensorDefaults to 0

Number of final positions, or integer positions to keep.

output_hidden_states
boolDefaults to False

Attach the final hidden states [batch, sequence, hidden].

pixel_values
torch.Tensor | NoneDefaults to None

Optional tensor of shape [patches, channels * patch_size * patch_size].

image_grid_thw
torch.Tensor | NoneDefaults to None

Optional integer tensor of shape [images, 3] of (time, height, width) patch counts.

mm_token_type_ids
torch.Tensor | NoneDefaults to None

Optional integer tensor of shape [batch, sequence], 0 text / 1 image.

cp_group
dist.ProcessGroup | NoneDefaults to None

Context-parallel group; the token tensors are then the shard from the model-owned sharder.

seq_lens
torch.Tensor | NoneDefaults to None

Optional integer tensor of shape [batch, documents] of document lengths of a packed row (non-CP); seq_lens_padded gives the physical spans and qkv_format must be "thd" or omitted.

Returns: CausalLMOutputWithPast

CausalLMOutputWithPast with logits [batch, kept_sequence, vocab].

classmethod

Construct using the NeMo registry’s configuration entry point.

nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM.get_input_embeddings() -> torch.nn.Embedding

Return the token embedding.

nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM.get_output_embeddings() -> torch.nn.Module

Return the independent vocabulary projection.

nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM.initialize_weights(
buffer_device: torch.device | None = None,
dtype: torch.dtype = torch.bfloat16
) -> None

Initialize every weight (checkpoint-free path) as the reference does.

nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForCausalLM.prepare_model_inputs_for_cp(
batch: dict[str, torch.Tensor],
num_chunks: int = 1

Select contiguous packed sharding (documents are never aligned or reordered).

batch holds full tensors [batch, global_sequence]; the returned model-owned sharder yields local token tensors of shape [1, padded_global_sequence / cp_size]. num_chunks is unused: this model uses one chunk.

class nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashModel(
engram_process_group: torch.distributed.ProcessGroup | None = None
)

Bases: Module

Embeddings, hyper-connected blocks and the output collapse.

embed_tokens
hc_head
= HYV4FlashHyperHead(config)
layers
norm
nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashModel.forward(
input_ids: torch.Tensor,
position_ids: torch.Tensor,
attention_mask: torch.Tensor | None = None,
packed_seq_ids: torch.Tensor | None = None,
inputs_embeds: torch.Tensor,
image_token_mask: torch.Tensor | None = None,
cp_group: torch.distributed.ProcessGroup | None = None
) -> torch.Tensor

Compute the final hidden states [batch, sequence, hidden].

inputs_embeds [batch, sequence, hidden] are the token embeddings with image features in place; the other arguments are those of prepare_batch.

nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashModel.prepare_batch(
input_ids: torch.Tensor,
position_ids: torch.Tensor,
attention_mask: torch.Tensor | None,
packed_seq_ids: torch.Tensor | None,
image_token_mask: torch.Tensor | None,
cp_group: torch.distributed.ProcessGroup | None = None

Build the flattened-token metadata shared by every layer.

Parameters:

input_ids
torch.Tensor

Integer tensor of shape [batch, sequence].

position_ids
torch.Tensor

Integer tensor of shape [3, batch, sequence] (time, height, width).

attention_mask
torch.Tensor | None

Optional bool/int tensor of shape [batch, sequence], 1 for real tokens.

packed_seq_ids
torch.Tensor | None

Optional integer tensor of shape [batch, sequence] with document ids (0 = padding).

image_token_mask
torch.Tensor | None

Optional bool tensor of shape [batch, sequence], True at image placeholder tokens.

cp_group
dist.ProcessGroup | NoneDefaults to None

Context-parallel group; all token tensors above then hold this rank’s contiguous shard (batch must be 1) and the returned document layout / rotary tables cover the global sequence.

Returns: HYV4FlashBatch

The shared batch view.

nemo_automodel.components.models.hy_v4_flash.model.build_moe_config(
dtype: torch.dtype

MoE settings of the latent-space sigmoid router (all routed experts run at routed_expert_hidden_size).

nemo_automodel.components.models.hy_v4_flash.model.compute_mrope_position_ids(
mm_token_type_ids: torch.Tensor,
image_grid_thw: torch.Tensor | None,
attention_mask: torch.Tensor | None,
merge: int
) -> torch.Tensor

M-RoPE positions of mixed text / image rows (the reference get_rope_index).

Text advances all three axes by one per token; an image block takes vision_position_ids and the next text token continues at max + 1. Padding positions get zero.

Parameters:

mm_token_type_ids
torch.Tensor

Integer tensor of shape [batch, sequence], 0 for text and 1 for image tokens.

image_grid_thw
torch.Tensor | None

Integer tensor of shape [images, 3] in row-major order of appearance, or None.

attention_mask
torch.Tensor | None

Optional tensor of shape [batch, sequence], 1 for real tokens.

merge
int

Spatial merge size.

Returns: torch.Tensor

Integer tensor of shape [3, batch, sequence].

nemo_automodel.components.models.hy_v4_flash.model.vision_position_ids(
start: int,
grid_thw: tuple[int, int, int],
merge: int
) -> torch.Tensor

3-D positions of one image/video: every merged row has w + 1 tokens (the last is the newline).

All three axes of a frame start at the same offset and each frame starts a new block of max(h, w + 1) positions.

Returns: torch.Tensor

Integer tensor of shape [3, t * h * (w + 1)] (time, height, width), offset by start.

nemo_automodel.components.models.hy_v4_flash.model.HYV4FlashForConditionalGeneration = HYV4FlashForCausalLM
nemo_automodel.components.models.hy_v4_flash.model.ModelClass = HYV4FlashForCausalLM