class Inkling2Model(nn.Module):
def __init__(
self,
config: Inkling2ModelConfig,
quant_config: Inkling2QuantConfig | None,
prefix: str,
) -> None:
super().__init__()
self.config = config
self.block_size = config.n_layers_per_attn_res_block
self.normalize_values = config.attn_res_normalize_values
self.embed_tokens = VocabParallelEmbedding(
config.padded_vocab_size, config.hidden_size
)
self.embed_norm = Inkling2RMSNorm(
config.hidden_size, config.rms_norm_eps, out_dtype=None
)
self.layers = nn.ModuleList(
Inkling2DecoderLayer(config, i, quant_config, f"{prefix}.layers.{i}")
for i in range(config.num_hidden_layers)
)
self.attn_res = Inkling2AttnRes(config)
self.norm = Inkling2RMSNorm(config.hidden_size, config.rms_norm_eps)
# Large batches keep a token shard of the hidden stream on each rank.
self.allreduce_workspace = None
self.seq_parallel = None
if get_tensor_model_parallel_world_size() > 1:
assert self.normalize_values
group = get_tp_group().cpu_group
self.allreduce_workspace = Inkling2AllReduceWorkspace.create(
group, config.hidden_size
)
if self.allreduce_workspace is not None:
vllm_config = get_current_vllm_config()
spec = vllm_config.speculative_config
num_spec = 0 if spec is None else spec.num_speculative_tokens
self.seq_parallel = SeqParallel(
group,
config.hidden_size,
vllm_config.scheduler_config.max_num_batched_tokens,
tail_rows=max(config.sconv_kernel_size - 1, num_spec + 1),
)
# Layers whose input (the partial block) the DSpark draft reads; layer
# id num_hidden_layers stands for the final-norm output.
self.aux_hidden_state_layers: tuple[int, ...] = ()
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.embed_norm(self.embed_tokens(input_ids))
def _mix(
self,
stack: torch.Tensor,
last: torch.Tensor,
query: torch.Tensor,
norm: Inkling2RMSNorm,
addend: torch.Tensor | None = None,
) -> torch.Tensor:
return attn_res(
stack, last, addend, query, norm.weight, norm.eps, self.normalize_values
)
def forward(
self, positions: torch.Tensor, inputs_embeds: torch.Tensor
) -> torch.Tensor | tuple[torch.Tensor, list[torch.Tensor]]:
num_tokens, hidden = inputs_embeds.shape
aux_hidden_states = []
num_layers = len(self.layers)
# With a conv-state cache (TP > 1), the hidden-stream conv runs fused
# with the next AttnRes mix: small batches also fuse each sublayer's
# all-reduce, larger ones run it on the all-reduced input. Large
# batches keep a token shard of the hidden stream on each rank
# (reduce-scatter, then `conv_mix`), also in profile runs (no
# conv-state cache) for their memory use.
workspace = self.allreduce_workspace
plan = [(False, False)] * 2
has_cache = conv_metadata(self.layers[0].conv_state) is not None
sp = self.seq_parallel
if sp is not None and num_tokens < sp.min_tokens:
sp = None
conv_mix = workspace is not None and has_cache
if conv_mix and sp is None:
assert workspace is not None
plan = workspace.plan(num_tokens)
(attn_fused, attn_two_shot), (moe_fused, moe_two_shot) = plan
# stack[:num_blocks] holds completed blocks; stack[num_blocks] is the
# running partial block (of this rank's shard of rows[:capacity]).
max_blocks = -(-num_layers // self.block_size)
begin, end, capacity = 0, num_tokens, num_tokens
prefix_align = 0
if sp is not None:
begin, end, capacity = sp.shard(num_tokens)
prefix_align = self._prefix_align() if has_cache else 0
stacked = inputs_embeds.new_empty((max_blocks + 1, capacity, hidden))
stack = stacked[:, : end - begin]
stack[0].copy_(inputs_embeds[begin:end])
num_blocks = 0
tau = None
if self.config.log_scaling_n_floor is not None:
tau = compute_log_scaling_tau(
positions,
self.config.log_scaling_n_floor,
self.config.log_scaling_alpha,
)
# The fused MoE all-reduce also produces the next layer's inputs.
inputs = None
for i, layer in enumerate(self.layers):
partial = stack[num_blocks]
if i in self.aux_hidden_state_layers:
if sp is None:
aux_hidden_states.append(partial.clone())
else:
aux_hidden_states.append(
tensor_model_parallel_all_gather(stacked[num_blocks], 0)[
:num_tokens
]
)
if inputs is None and num_blocks == 0:
# The shard of the first block holds this rank's rows only.
first_in = partial if sp is None else inputs_embeds
inputs = [
layer.attn_norm(first_in, j) for j in range(layer.num_attn_inputs)
]
elif inputs is None:
query = self.attn_res.attn_queries[i - 1]
inputs = self._mix(stack[:num_blocks], partial, query, layer.attn_norm)
attn_partial = layer.attention(
positions,
inputs,
tau,
out=None if sp is None else sp.partial(num_tokens),
)
mlp_query = self.attn_res.mlp_queries[i]
# The MLP input mixes the blocks with (partial +) attn_out.
first = i % self.block_size == 0
if sp is not None or conv_mix:
attn_out = torch.empty_like(partial)
mix_args = (
positions,
attn_out,
stack[: num_blocks + first],
None if first else partial,
mlp_query,
layer.mlp_norm,
)
if sp is not None:
shard, halo = sp.reduce_scatter(num_tokens)
mlp_in = layer.attn_sconv.conv_mix(
shard, *mix_args, sp=sp, halo=halo, prefix_align=prefix_align
)
elif attn_fused:
assert workspace is not None
mlp_in = layer.attn_sconv.all_reduce_mix(
workspace, *mix_args, x=attn_partial, two_shot=attn_two_shot
)
else:
attn_reduced = tensor_model_parallel_all_reduce(attn_partial)
mlp_in = layer.attn_sconv.conv_mix(attn_reduced, *mix_args)
else:
attn_out = layer.attn_sconv(
tensor_model_parallel_all_reduce(attn_partial), positions
)
if first:
mlp_in = self._mix(
stack[: num_blocks + 1], attn_out, mlp_query, layer.mlp_norm
)
else:
mlp_in = self._mix(
stack[:num_blocks], partial, mlp_query, layer.mlp_norm, attn_out
)
# The MLP short conv also applies the residual update.
residual = None if first else partial
if residual is None:
num_blocks += 1
inputs = None
if sp is None and not conv_mix:
layer.mlp_sconv(
layer.mlp(mlp_in[0]),
positions,
addend=attn_out,
residual=residual,
out=stack[num_blocks],
)
continue
if i + 1 < num_layers:
query = self.attn_res.attn_queries[i]
norm = self.layers[i + 1].attn_norm
else:
query, norm = self.attn_res.output_query, self.norm
mix_args = (
positions,
stack[num_blocks],
stack[:num_blocks],
None,
query,
norm,
)
if sp is not None:
layer.mlp(mlp_in[0], reduce=False, push=sp)
shard, halo = sp.pushed(num_tokens)
inputs = layer.mlp_sconv.conv_mix(
shard,
*mix_args,
addend=attn_out,
residual=residual,
sp=sp,
halo=halo,
prefix_align=prefix_align,
)
elif moe_fused:
assert workspace is not None
inputs = layer.mlp_sconv.all_reduce_mix(
workspace,
*mix_args,
combine=layer.mlp(mlp_in[0], reduce=False),
addend=attn_out,
residual=residual,
two_shot=moe_two_shot,
)
else:
# The MoE output is all-reduced (in bf16) inside layer.mlp.
moe_reduced = layer.mlp(mlp_in[0])
inputs = layer.mlp_sconv.conv_mix(
moe_reduced, *mix_args, addend=attn_out, residual=residual
)
if inputs is not None:
# The all-gather buffer is reused by the next forward.
out = inputs[0] if sp is None else inputs[0].clone()
else:
out = self._mix(
stack[:num_blocks],
stack[num_blocks],
self.attn_res.output_query,
self.norm,
)[0]
if self.aux_hidden_state_layers:
return out, [*aux_hidden_states, out]
return out
def _prefix_align(self) -> int:
"""A token multiple of every prefix-cache hit (a KV cache block size
of the full-attention layers)."""
layer = next(layer for layer in self.layers if not layer.is_local)
return layer.attn.kv_cache.shape[2]