Skip to content

llmcompressor.modeling.kimi_k3.modeling_kimi_k3

Classes:

Functions:

KimiK3ForConditionalGeneration

KimiK3ForConditionalGeneration(
    config: KimiK3Config, **kwargs
)

Bases: KimiK3PreTrainedModel

Methods:

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def __init__(self, config: KimiK3Config, **kwargs):
    super().__init__(config)

    vt_config = VisionTowerConfig(config.vision_config)
    self.vision_tower = MoonViT3dPretrainedModel(vt_config)

    proj_config = ProjectorConfig(config.vision_config)
    if proj_config.mm_projector_type == "identity":
        self.mm_projector = IdentityMap()
    elif proj_config.mm_projector_type == "mlp":
        self.mm_projector = MLP(proj_config)
    elif proj_config.mm_projector_type == "patchmerger":
        self.mm_projector = PatchMergerMLP(proj_config)
    elif proj_config.mm_projector_type == "patchmergerv2":
        self.mm_projector = PatchMergerMLPV2(proj_config)
    else:
        raise ValueError(
            f"Unsupported mm_projector_type: {proj_config.mm_projector_type}"
        )

    self.language_model = KimiLinearForCausalLM(config.text_config)
    self.post_init()

    if hasattr(self.language_model, "dtype"):
        target_dtype = self.language_model.dtype
        self.vision_tower = self.vision_tower.to(dtype=target_dtype)
        self.mm_projector = self.mm_projector.to(dtype=target_dtype)

forward

forward(
    input_ids: LongTensor | None = None,
    pixel_values: FloatTensor
    | list[FloatTensor]
    | None = None,
    grid_thws: Tensor | None = None,
    attention_mask: Tensor | None = None,
    position_ids: LongTensor | 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,
    return_dict: bool | None = None,
) -> tuple | LlavaCausalLMOutputWithPast

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

```

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def forward(
    self,
    input_ids: torch.LongTensor | None = None,
    pixel_values: torch.FloatTensor | list[torch.FloatTensor] | None = None,
    grid_thws: torch.Tensor | None = None,
    attention_mask: torch.Tensor | None = None,
    position_ids: torch.LongTensor | None = None,
    past_key_values: list[torch.FloatTensor] | None = None,
    inputs_embeds: torch.FloatTensor | None = None,
    labels: torch.LongTensor | None = None,
    use_cache: bool | None = None,
    output_attentions: bool | None = None,
    output_hidden_states: bool | None = None,
    return_dict: bool | None = None,
) -> tuple | LlavaCausalLMOutputWithPast:
    r"""
    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]`.

    ```"""
    assert self.vision_tower is not None, "vision_tower is not loaded"
    output_attentions = (
        output_attentions
        if output_attentions is not None
        else self.config.output_attentions
    )
    output_hidden_states = (
        output_hidden_states
        if output_hidden_states is not None
        else self.config.output_hidden_states
    )
    return_dict = (
        return_dict if return_dict is not None else self.config.use_return_dict
    )

    if inputs_embeds is None:
        # 1. Extra the input embeddings
        inputs_embeds = self.get_input_embeddings()(input_ids)

        # 2. Merge text and images
        if (
            pixel_values is not None
            and len(pixel_values) > 0
            and input_ids.shape[1] != 1
        ):
            image_features = self._extract_image_features(pixel_values, grid_thws)
            if self.mm_projector:
                image_features = self.mm_projector(image_features)

            inputs_embeds = inputs_embeds.to(
                image_features[0].dtype
            )  # num_tokens, embed_dim
            inputs_embeds, attention_mask, labels, position_ids = (
                self._merge_input_ids_with_image_features(
                    image_features,
                    inputs_embeds,
                    input_ids,
                    attention_mask,
                    labels,
                )
            )

        # In case input_ids.shape[1] == 1 & pixel_values==None & past_key_values != None, we are in the case of
        # generation with cache
        elif (
            past_key_values is not None
            and pixel_values is not None
            and input_ids.shape[1] == 1
        ):
            # Retrieve the first layer to inspect the logits and mask out the hidden states
            # that are set to 0
            first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]

            # Sum all dimensions of head_dim (-2) to avoid random errors such as: https://github.com/huggingface/transformers/pull/28032#issuecomment-1863691941
            batch_index, non_attended_tokens = torch.where(
                first_layer_past_key_value.float().sum(-2) == 0
            )

            # Get the target length
            target_length = input_ids.shape[1]
            past_length = first_layer_past_key_value.shape[-1]

            extended_attention_mask = torch.ones(
                (attention_mask.shape[0], past_length),
                dtype=attention_mask.dtype,
                device=attention_mask.device,
            )

            # Filter out only the tokens that can be un-attended, this can happen
            # if one uses Llava + Fused modules where the cache on the
            # first iteration is already big enough, or if one passes custom cache
            valid_indices = non_attended_tokens < extended_attention_mask.size(-1)
            new_batch_index = batch_index[valid_indices]
            new_non_attended_tokens = non_attended_tokens[valid_indices]

            # Zero-out the places where we don't need to attend
            extended_attention_mask[new_batch_index, new_non_attended_tokens] = 0

            attention_mask = torch.cat(
                (extended_attention_mask, attention_mask[:, -target_length:]), dim=1
            )
            position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1

    outputs = self.language_model(
        attention_mask=attention_mask,
        position_ids=position_ids,
        past_key_values=past_key_values,
        inputs_embeds=inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    logits = outputs[0]

    loss = None
    if labels is not None:
        # Shift so that tokens < n predict n
        if attention_mask is not None:
            shift_attention_mask = attention_mask[..., 1:]
            shift_logits = logits[..., :-1, :][
                shift_attention_mask.to(logits.device) != 0
            ].contiguous()
            shift_labels = labels[..., 1:][
                shift_attention_mask.to(labels.device) != 0
            ].contiguous()
        else:
            shift_logits = logits[..., :-1, :].contiguous()
            shift_labels = labels[..., 1:].contiguous()
        # Flatten the tokens
        loss_fct = nn.CrossEntropyLoss()
        loss = loss_fct(
            shift_logits.view(-1, shift_logits.size(-1)),
            shift_labels.view(-1).to(shift_logits.device),
        )

    if not return_dict:
        output = (logits,) + outputs[1:]
        return (loss,) + output if loss is not None else output

    return LlavaCausalLMOutputWithPast(
        loss=loss,
        logits=logits,
        past_key_values=outputs.past_key_values,
        hidden_states=outputs.hidden_states,
        attentions=outputs.attentions,
    )

MLP2

MLP2(dims: list[int], activation, bias=True)

Bases: Module

Args: dims: [in_dim, hidden_dim, out_dim] bias: whether to use bias in linear layer.

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def __init__(self, dims: list[int], activation, bias=True):
    super().__init__()
    assert len(dims) == 3
    self.fc0 = nn.Linear(dims[0], dims[1], bias=bias)
    self.fc1 = nn.Linear(dims[1], dims[2], bias=bias)
    self.activation = activation
    for m in [self.fc0, self.fc1]:
        nn.init.trunc_normal_(m.weight, std=math.sqrt(2 / m.in_features))
        if m.bias is not None:
            nn.init.zeros_(m.bias)

MoonViT3dPretrainedModel

MoonViT3dPretrainedModel(config, *inputs, **kwargs)

Bases: PreTrainedModel

Methods:

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def __init__(self, config, *inputs, **kwargs):
    super().__init__(config, *inputs, **kwargs)
    config = deepcopy(config)
    self.merge_kernel_size = config.merge_kernel_size
    self.patch_size = config.patch_size
    self.merge_type = config.merge_type

    self.patch_embed = MoonVision3dPatchEmbed(
        out_dim=config.hidden_size,
        patch_size=config.patch_size,
        pos_emb_height=config.init_pos_emb_height,
        pos_emb_width=config.init_pos_emb_width,
        pos_emb_time=config.init_pos_emb_time,
        pos_emb_type=config.pos_emb_type,
        patch_embed_proj_bias=getattr(config, "patch_embed_proj_bias", True),
        pos_emb_interpolation_mode=getattr(
            config, "pos_emb_interpolation_mode", "bicubic"
        ),
    )

    self.encoder = MoonViT3dEncoder(
        hidden_dim=config.hidden_size,
        num_layers=config.num_hidden_layers,
        block_cfg={
            "num_heads": config.num_attention_heads,
            "hidden_dim": config.hidden_size,
            "qkv_hidden_size": getattr(config, "qkv_hidden_size", None),
            "mlp_dim": config.intermediate_size,
            "norm_type": getattr(config, "norm_type", "layernorm"),
            "mlp_type": getattr(config, "mlp_type", "mlp2"),
            "activation": PytorchGELUTanh(),
            "attn_bias": getattr(config, "attn_bias", True),
            "linear_bias": getattr(config, "linear_bias", True),
            "attn_implementation": config._attn_implementation,
        },
        use_deterministic_attn=getattr(self, "use_deterministic_attn", False),
    )

forward

forward(
    pixel_values: Tensor, grid_thws: Tensor
) -> torch.Tensor

Args: pixel_values (torch.Tensor): The input pixel values. grid_thws (torch.Tensor): Temporal, height and width.

Returns: torch.Tensor: The output tokens.

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def forward(
    self, pixel_values: torch.Tensor, grid_thws: torch.Tensor
) -> torch.Tensor:
    """
    Args:
        pixel_values (torch.Tensor): The input pixel values.
        grid_thws (torch.Tensor): Temporal, height and width.

    Returns:
        torch.Tensor: The output tokens.
    """
    # grid_thws = grid_thws.to('cpu')
    assert grid_thws.ndim == 2, f"grid_thws should be 2D, got {grid_thws.ndim}"
    assert grid_thws.size(1) == 3, f"No support for thw: {grid_thws}"
    hidden_states = self.patch_embed(pixel_values, grid_thws)
    hidden_states = self.encoder(hidden_states, grid_thws)
    if (
        self.merge_type == "sd2_tpool"
    ):  # spatial downsampling 2x with temporal pooling all
        hidden_states = tpool_patch_merger(
            hidden_states, grid_thws, merge_kernel_size=self.merge_kernel_size
        )
    else:
        raise NotImplementedError(f"Not support {self.merge_type}")

    return hidden_states

MoonViTEncoderLayer

MoonViTEncoderLayer(
    num_heads: int,
    hidden_dim: int,
    mlp_dim: int,
    qkv_hidden_size: int | None = None,
    norm_type: str = "layernorm",
    mlp_type: str = "mlp2",
    *,
    attn_implementation: str = "flash_attention_2",
    activation=F.gelu,
    attn_bias: bool = False,
    linear_bias: bool = True,
    use_deterministic_attn: bool = False,
)

Bases: Module

Methods:

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def __init__(
    self,
    num_heads: int,
    hidden_dim: int,
    mlp_dim: int,
    qkv_hidden_size: int | None = None,
    norm_type: str = "layernorm",
    mlp_type: str = "mlp2",
    *,
    attn_implementation: str = "flash_attention_2",
    activation=F.gelu,
    attn_bias: bool = False,
    linear_bias: bool = True,
    use_deterministic_attn: bool = False,
):
    super().__init__()
    self.num_heads = num_heads
    self.hidden_dim = hidden_dim
    self.qkv_hidden_size = (
        hidden_dim if qkv_hidden_size is None else qkv_hidden_size
    )
    self.hidden_size_per_attention_head = self.qkv_hidden_size // self.num_heads
    self.attn_implementation = attn_implementation
    self.use_deterministic_attn = use_deterministic_attn

    if norm_type == "layernorm":
        self.norm0 = nn.LayerNorm(hidden_dim)
        self.norm1 = nn.LayerNorm(hidden_dim)
    elif norm_type == "rmsnorm":
        self.norm0 = nn.RMSNorm(hidden_dim)
        self.norm1 = nn.RMSNorm(hidden_dim)
    else:
        raise NotImplementedError(f"Not support norm_type: {norm_type}")

    if mlp_type == "mlp2":
        self.mlp = MLP2(
            [hidden_dim, mlp_dim, hidden_dim], activation, bias=linear_bias
        )
    else:
        raise NotImplementedError(f"Not support mlp_type: {mlp_type}")

    self.wqkv = nn.Linear(hidden_dim, self.qkv_hidden_size * 3, bias=attn_bias)
    self.wo = nn.Linear(self.qkv_hidden_size, hidden_dim, bias=attn_bias)

attention_qkvpacked

attention_qkvpacked(
    x: Tensor,
    cu_seqlens: Tensor,
    max_seqlen: Tensor,
    rope_freqs_cis: Tensor | None = None,
)

Args: x (torch.Tensor): (batch_size, seqlen, hidden_dim) cu_seqlens (torch.Tensor):

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def attention_qkvpacked(
    self,
    x: torch.Tensor,
    cu_seqlens: torch.Tensor,
    max_seqlen: torch.Tensor,
    rope_freqs_cis: torch.Tensor | None = None,
):
    """
    Args:
        x (torch.Tensor): (batch_size, seqlen, hidden_dim)
        cu_seqlens (torch.Tensor):
    """
    xqkv = self.wqkv(x)

    qkv_shape = xqkv.size()[:-1] + (
        3,
        self.num_heads,
        self.hidden_size_per_attention_head,
    )
    # xqkv: (batch_size, seqlen, 3, nheads, headdim)
    xqkv = xqkv.view(*qkv_shape)
    xq, xk, xv = torch.unbind(xqkv, dim=-3)

    xq, xk = apply_rope(xq, xk, rope_freqs_cis)

    attn_func = VL_VISION_ATTENTION_FUNCTIONS[self.attn_implementation]
    attn_out = attn_func(
        xq,
        xk,
        xv,
        q_cu_seqlens=cu_seqlens,
        k_cu_seqlens=cu_seqlens,
        max_seqlen_k=max_seqlen,
        max_seqlen_q=max_seqlen,
        deterministic=self.use_deterministic_attn,
    )

    attn_out = self.wo(attn_out)
    return attn_out

MoonVision3dPatchEmbed

MoonVision3dPatchEmbed(
    out_dim: int,
    in_dim: int = 3,
    patch_size: int | tuple[int, int] = (14, 14),
    pos_emb_height: int = 14,
    pos_emb_width: int = 14,
    pos_emb_time: int = 4,
    pos_emb_type: str = "divided_fixed",
    patch_embed_proj_bias: bool = True,
    pos_emb_interpolation_mode: str = "bicubic",
)

Bases: Module

Methods:

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def __init__(
    self,
    out_dim: int,
    in_dim: int = 3,
    patch_size: int | tuple[int, int] = (14, 14),
    pos_emb_height: int = 14,
    pos_emb_width: int = 14,
    pos_emb_time: int = 4,
    pos_emb_type: str = "divided_fixed",
    patch_embed_proj_bias: bool = True,
    pos_emb_interpolation_mode: str = "bicubic",
):
    super().__init__()
    assert isinstance(
        patch_size, int | Sequence
    ), f"Invalid patch_size type: {type(patch_size)}"
    if isinstance(patch_size, int):
        patch_size = (patch_size, patch_size)
    assert (
        len(patch_size) == 2
    ), f"Expected patch_size to be a tuple of 2, got {patch_size}"
    self.patch_size = patch_size

    self.proj = nn.Conv2d(
        in_dim,
        out_dim,
        kernel_size=patch_size,
        stride=patch_size,
        bias=patch_embed_proj_bias,
    )

    if pos_emb_type == "divided_fixed":
        self.pos_emb = Learnable2DInterpPosEmbDivided_fixed(
            height=pos_emb_height,
            width=pos_emb_width,
            num_frames=pos_emb_time,
            dim=out_dim,
            interpolation_mode=pos_emb_interpolation_mode,
        )
    else:
        raise NotImplementedError(f"Not support pos_emb_type: {pos_emb_type}")

forward

forward(x: Tensor, grid_thws: Tensor) -> torch.Tensor

Args: x (L, Channels): input tensor grid_hws (N, 3): temporal, height and width

Returns: (L, Cout) tensor

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def forward(self, x: torch.Tensor, grid_thws: torch.Tensor) -> torch.Tensor:
    """
    Args:
        x (L, Channels): input tensor
        grid_hws (N, 3): temporal, height and width

    Returns:
        (L, Cout) tensor
    """
    x = self.proj(x).view(x.size(0), -1)
    # apply positional embedding
    x = self.pos_emb(x, grid_thws)
    return x

Rope2DPosEmbRepeated

Rope2DPosEmbRepeated(
    dim: int,
    max_height: int,
    max_width: int,
    theta_base=10000,
)

Bases: Module

2D rotary position embedding with multi-resolution support.

This class is intended to be used in the following way: 1. Before training, create an instance of Rope2DPosEmb. This instance will hold the precomputed cis. 2. Before each forward pass, call get_freqs_cis_by_* to get the freqs_cis tensor for this iteration. 3. During the forward pass, pass the freqs_cis tensor to each attention layer, and call apply just before each attention operation. The rope is shared across all attention layers and all heads.

Refs: - RoFormer: https://arxiv.org/abs/2104.09864 - VisionLLaMA: https://arxiv.org/abs/2403.00522 - https://github.com/Meituan-AutoML/VisionLLaMA/blob/main/dit/models.py

Args: dim (int): usually the multi-head attention dimension, should be divisible by 4 (TODO: relax this constraint if needed) max_height (int): the maximum height of the 2D grid max_width (int): the maximum width of the 2D grid theta_base (float): the base of the theta device (str): the device to store the precomputed cis

Methods:

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def __init__(self, dim: int, max_height: int, max_width: int, theta_base=10000):
    super().__init__()
    self.dim = dim
    assert self.dim % 4 == 0, "dim must be divisible by 4"
    self.max_height = max_height
    self.max_width = max_width
    self.theta_base = theta_base

get_freqs_cis

get_freqs_cis(
    grid_thws: Tensor, device: device
) -> torch.Tensor

Args: grid_thws (torch.Tensor): grid time, height and width

Returns: freqs_cis: tensor of shape (sum(t * height * width), dim//2)

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def get_freqs_cis(
    self, grid_thws: torch.Tensor, device: torch.device
) -> torch.Tensor:
    """
    Args:
        grid_thws (torch.Tensor): grid time, height and width

    Returns:
        freqs_cis: tensor of shape (sum(t * height * width), dim//2)
    """
    if not hasattr(self, "freqs_cis"):
        self.register_buffer(
            "freqs_cis", self._precompute_freqs_cis(device), persistent=False
        )

    shapes = grid_thws.tolist()
    assert all(
        1 <= h <= self.max_height and 1 <= w <= self.max_width for t, h, w in shapes
    ), (
        shapes,
        self.max_height,
        self.max_width,
    )
    freqs_cis = torch.cat(
        [
            self.freqs_cis[:h, :w].reshape(-1, self.dim // 2).repeat(t, 1)
            for t, h, w in shapes
        ],
        dim=0,
    )
    return freqs_cis

apply_rope

apply_rope(
    xq: Tensor, xk: Tensor, freqs_cis: Tensor
) -> tuple[torch.Tensor, torch.Tensor]

Args: (The leading dimensions of all inputs should be the same) xq: query, tensor of shape (..., num_heads, head_dim) xk: key, tensor of shape (..., num_heads, head_dim) freqs_cis: tensor of shape (..., head_dim/2), dtype=torch.complex64. It contains the precomputed cis(freqs) for each position in the 2D grid. Returns: xq_out, xk_out: tensors of shape (..., num_heads, head_dim)

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def apply_rope(
    xq: torch.Tensor, xk: torch.Tensor, freqs_cis: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    Args: (The leading dimensions of all inputs should be the same)
        xq: query, tensor of shape (..., num_heads, head_dim)
        xk: key, tensor of shape (..., num_heads, head_dim)
        freqs_cis: tensor of shape (..., head_dim/2), dtype=torch.complex64. It contains the precomputed cis(freqs) for each position in the 2D grid.
    Returns:
        xq_out, xk_out: tensors of shape (..., num_heads, head_dim)
    """
    _apply_rope_input_validation(xq, freqs_cis)
    _apply_rope_input_validation(xk, freqs_cis)

    freqs_cis = freqs_cis.unsqueeze(-2)  # ..., 1, head_dim/2
    # ..., num_heads, head_dim/2
    xq_ = torch.view_as_complex(xq.float().view(*xq.shape[:-1], -1, 2))
    xk_ = torch.view_as_complex(xk.float().view(*xq.shape[:-1], -1, 2))
    xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(-2)  # ..., num_heads, head_dim
    xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(-2)  # ..., num_heads, head_dim
    return xq_out.type_as(xq), xk_out.type_as(xk)

get_1d_sincos_pos_embed

get_1d_sincos_pos_embed(embed_dim, t_size, cls_token=False)

t_size: int of the temporal size return: pos_embed: [t_size, embed_dim] or [1+t_size, embed_dim] (w/ or w/o cls_token)

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def get_1d_sincos_pos_embed(embed_dim, t_size, cls_token=False):
    """
    t_size: int of the temporal size
    return:
    pos_embed: [t_size, embed_dim] or [1+t_size, embed_dim] (w/ or w/o cls_token)
    """
    grid_t = np.arange(t_size, dtype=np.float32)
    pos_embed = get_1d_sincos_pos_embed_from_grid(embed_dim, grid_t)
    if cls_token:
        pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
    return pos_embed

get_1d_sincos_pos_embed_from_grid

get_1d_sincos_pos_embed_from_grid(embed_dim, pos)

From: https://github.com/OpenGVLab/InternVideo/blob/421f6d2361fc8f61a3394244571f2601a4e99e29/InternVideo2/multi_modality/models/backbones/internvideo2/pos_embed.py#L86 embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
    """
    From:
    https://github.com/OpenGVLab/InternVideo/blob/421f6d2361fc8f61a3394244571f2601a4e99e29/InternVideo2/multi_modality/models/backbones/internvideo2/pos_embed.py#L86
    embed_dim: output dimension for each position
    pos: a list of positions to be encoded: size (M,)
    out: (M, D)
    """
    assert embed_dim % 2 == 0
    omega = np.arange(embed_dim // 2, dtype=np.float32)
    omega /= embed_dim / 2.0
    omega = 1.0 / 10000**omega  # (D/2,)

    pos = pos.reshape(-1)  # (M,)
    out = np.einsum("m,d->md", pos, omega)  # (M, D/2), outer product

    emb_sin = np.sin(out)  # (M, D/2)
    emb_cos = np.cos(out)  # (M, D/2)

    emb = np.concatenate([emb_sin, emb_cos], axis=1)  # (M, D)
    return emb

multihead_attention

multihead_attention(
    q: Tensor,
    k: Tensor,
    v: Tensor,
    q_cu_seqlens: Tensor | None = None,
    k_cu_seqlens: Tensor | None = None,
    max_seqlen_q: int | None = None,
    max_seqlen_k: int | None = None,
    deterministic: bool = False,
)

Multi-head attention using flash attention 2.

Args: q, k, v: tensor of shape (batch_size, seqlen, num_heads, head_dim), or (tot_seqlens, num_heads, head_dim) if packing. q_cu_seqlens (torch.Tensor): cumulative sequence lengths of q. The first element should be 0 and the last element should be q.shape[0]. k_cu_seqlens (torch.Tensor): cumulative sequence lengths of k. The first element should be 0 and the last element should be k.shape[0].

Returns: output: shape (batch_size, seqlen, dim) or (tot_seqlens, dim) if packing, where dim = num_heads * head_dim

Source code in src/llmcompressor/modeling/kimi_k3/modeling_kimi_k3.py
def multihead_attention(
    q: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    q_cu_seqlens: torch.Tensor | None = None,
    k_cu_seqlens: torch.Tensor | None = None,
    max_seqlen_q: int | None = None,
    max_seqlen_k: int | None = None,
    deterministic: bool = False,
):
    """Multi-head attention using flash attention 2.

    Args:
        q, k, v: tensor of shape (batch_size, seqlen, num_heads, head_dim),
            or (tot_seqlens, num_heads, head_dim) if packing.
        q_cu_seqlens (torch.Tensor): cumulative sequence lengths of q.
            The first element should be 0 and the last element should be q.shape[0].
        k_cu_seqlens (torch.Tensor): cumulative sequence lengths of k.
            The first element should be 0 and the last element should be k.shape[0].

    Returns:
        output: shape (batch_size, seqlen, dim) or (tot_seqlens, dim) if packing,
            where dim = num_heads * head_dim
    """
    attn_out = flash_attn_varlen_func(
        q,
        k,
        v,
        q_cu_seqlens,
        k_cu_seqlens,
        max_seqlen_q,
        max_seqlen_k,
        causal=False,
        deterministic=deterministic,
    )
    if isinstance(attn_out, tuple):
        attn_out = attn_out[0]

    attn_out = attn_out.flatten(start_dim=-2)

    return attn_out