gemma3n.py 43.2 KB
Newer Older
Robert Shaw's avatar
Robert Shaw committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Copyright 2025 The vLLM team.
# Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections.abc import Iterable

import torch
from torch import nn
from transformers.models.gemma3n.configuration_gemma3n import Gemma3nTextConfig

24
from vllm.attention.layer import Attention
Robert Shaw's avatar
Robert Shaw committed
25
26
27
from vllm.compilation.decorators import support_torch_compile
from vllm.config import CacheConfig, VllmConfig
from vllm.distributed import get_tensor_model_parallel_world_size
28
from vllm.forward_context import get_forward_context
Robert Shaw's avatar
Robert Shaw committed
29
from vllm.logger import init_logger
30
31
32
33
34
from vllm.model_executor.layers.activation import (
    _ACTIVATION_REGISTRY,
    GeluAndMul,
    GeluAndMulSparse,
)
Robert Shaw's avatar
Robert Shaw committed
35
from vllm.model_executor.layers.layernorm import RMSNorm
36
37
38
39
40
41
42
from vllm.model_executor.layers.linear import (
    ColumnParallelLinear,
    MergedColumnParallelLinear,
    QKVParallelLinear,
    ReplicatedLinear,
    RowParallelLinear,
)
Robert Shaw's avatar
Robert Shaw committed
43
44
45
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.rotary_embedding import get_rope
46
from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding
Robert Shaw's avatar
Robert Shaw committed
47
from vllm.model_executor.model_loader.weight_utils import (
48
49
50
    default_weight_loader,
    maybe_remap_kv_scale_name,
)
Robert Shaw's avatar
Robert Shaw committed
51
from vllm.sequence import IntermediateTensors
52
from vllm.v1.attention.backends.utils import KVSharingFastPrefillMetadata
Robert Shaw's avatar
Robert Shaw committed
53

54
from .interfaces import SupportsQuant
55
56
57
58
59
60
61
from .utils import (
    AutoWeightsLoader,
    extract_layer_index,
    is_pp_missing_parameter,
    make_layers,
    maybe_prefix,
)
Robert Shaw's avatar
Robert Shaw committed
62
63
64

logger = init_logger(__name__)

65
66
EPS = torch.tensor(torch.finfo().min)

Robert Shaw's avatar
Robert Shaw committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

class Gemma3nAltUp(nn.Module):
    """Alternating updates (Altup)
    The AltUp module wraps transformer layers. The `predict` step modifies the
    input to the transformer layer, and the `correct` step propagates the output
    of the transformer layer to the sparsely updated dimensions.
    See more in the research paper:
    https://proceedings.neurips.cc/paper_files/paper/2023/file/f2059277ac6ce66e7e5543001afa8bb5-Paper-Conference.pdf
    """

    def __init__(
        self,
        hidden_size: int,
        rms_norm_eps: float,
        altup_num_inputs: int,
        altup_coef_clip: float,
        altup_active_idx: int,
84
        quant_config: QuantizationConfig,
Robert Shaw's avatar
Robert Shaw committed
85
86
87
88
89
90
91
92
93
94
95
96
        prefix: str,
    ):
        super().__init__()

        self.altup_num_inputs = altup_num_inputs
        self.altup_active_idx = altup_active_idx
        self.altup_coef_clip = altup_coef_clip

        self.correction_coefs = ReplicatedLinear(
            altup_num_inputs,
            altup_num_inputs,
            bias=False,
97
            quant_config=quant_config,
Robert Shaw's avatar
Robert Shaw committed
98
99
100
101
102
103
104
            prefix=f"{prefix}.correction_coefs",
            return_bias=False,
        )
        self.prediction_coefs = ReplicatedLinear(
            altup_num_inputs,
            altup_num_inputs**2,
            bias=False,
105
            quant_config=quant_config,
Robert Shaw's avatar
Robert Shaw committed
106
107
108
109
110
111
112
            prefix=f"{prefix}.prediction_coefs",
            return_bias=False,
        )
        self.modality_router = ReplicatedLinear(
            hidden_size,
            altup_num_inputs,
            bias=False,
113
            quant_config=quant_config,
Robert Shaw's avatar
Robert Shaw committed
114
115
116
117
118
119
120
121
            prefix=f"{prefix}.modality_router",
            return_bias=False,
        )
        self.router_norm = RMSNorm(
            hidden_size=hidden_size,
            eps=rms_norm_eps,
        )
        self.router_input_scale = torch.tensor(
122
123
            hidden_size**-1.0, dtype=self.modality_router.weight.dtype
        )
Robert Shaw's avatar
Robert Shaw committed
124
        self.correct_output_scale = nn.Parameter(
125
126
            torch.zeros(hidden_size, dtype=torch.float32)
        )
Robert Shaw's avatar
Robert Shaw committed
127
128
129
130
131
132
133

    def _compute_router_modalities(self, x: torch.Tensor) -> torch.Tensor:
        router_inputs = self.router_norm(x) * self.router_input_scale
        routed = self.modality_router(router_inputs)
        return torch.tanh(routed.float()).type_as(x)

    def scale_corrected_output(self, corrected: torch.Tensor) -> torch.Tensor:
134
135
136
        return (
            corrected.type_as(self.correct_output_scale) * self.correct_output_scale
        ).type_as(corrected)
Robert Shaw's avatar
Robert Shaw committed
137
138
139
140
141
142

    def predict(self, hidden_states: torch.Tensor) -> torch.Tensor:
        # hidden:       [altup_num_inputs, num_tokens, hidden_size]
        # modalities:   [num_tokens, num_altup_inputs]
        # all_coefs:    [num_tokens, num_altup_inputs ** 2]
        modalities = self._compute_router_modalities(
143
144
            hidden_states[self.altup_active_idx]
        )
Robert Shaw's avatar
Robert Shaw committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
        all_coefs = self.prediction_coefs(modalities)

        # Reshape and transpose the 2D matrix for the matmul.
        # all_coefs_T:  [num_tokens, num_altup_inputs, num_altup_inputs]
        all_coefs_T = all_coefs.reshape(
            -1,
            self.altup_num_inputs,
            self.altup_num_inputs,
        ).permute(0, 2, 1)

        # hidden_states to [num_tokens, hidden_size, altup_num_inputs]
        predictions = torch.matmul(hidden_states.permute(1, 2, 0), all_coefs_T)
        # [altup_num_inputs, num_tokens, hidden_size]
        predictions = predictions.permute(2, 0, 1)
        predictions += hidden_states
        return predictions.contiguous()

162
163
164
    def correct(
        self, predictions: torch.Tensor, activated: torch.Tensor
    ) -> torch.Tensor:
Robert Shaw's avatar
Robert Shaw committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
        # predictions:  [altup_num_inputs, num_tokens, hidden_size]
        # activated:    [num_tokens, hidden_size]
        # modalities:   [num_tokens, altup_num_inputs]
        modalities = self._compute_router_modalities(activated)
        # innovation:   [num_tokens, altup_num_inputs]
        innovation = activated - predictions[self.altup_active_idx]
        # innovation:   [altup_num_inputs, num_tokens, hidden_size]
        innovation = innovation.repeat(self.altup_num_inputs, 1, 1)

        # Permute to [altup_num_inputs, num_tokens] as the last dim
        # is a scalar applied to each altup input and expand on
        # num_tokens dim for broadcastability over hidden_size.
        # all_coefs:    [num_tokens, altup_num_inputs]
        all_coefs = self.correction_coefs(modalities) + 1.0
        # all_coefs:    [altup_num_inputs, num_tokens, 1]
        all_coefs = all_coefs.T.unsqueeze(-1)

        # Elementwise (broadcast over hidden_size).
        corrected = torch.mul(innovation, all_coefs)
        corrected += predictions

        return corrected.contiguous()


class Gemma3nLaurelBlock(nn.Module):
    """Learned Augmented Residual Layer"""

192
193
194
195
196
197
    def __init__(
        self,
        hidden_size: int,
        laurel_rank: int,
        rms_norm_eps: float,
        *,
198
        quant_config: QuantizationConfig | None = None,
199
200
        prefix: str,
    ) -> None:
Robert Shaw's avatar
Robert Shaw committed
201
202
203
204
205
206
        super().__init__()

        self.linear_left = ColumnParallelLinear(
            hidden_size,
            laurel_rank,
            bias=False,
207
            quant_config=quant_config,
Robert Shaw's avatar
Robert Shaw committed
208
209
210
            prefix=f"{prefix}.linear_left",
            return_bias=False,
        )
211
212
213
214
215
216
217
218
        self.linear_right = RowParallelLinear(
            laurel_rank,
            hidden_size,
            bias=False,
            quant_config=quant_config,
            prefix=f"{prefix}.linear_right",
            return_bias=False,
        )
Robert Shaw's avatar
Robert Shaw committed
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
        self.post_laurel_norm = RMSNorm(
            hidden_size=hidden_size,
            eps=rms_norm_eps,
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        laurel_x = self.linear_left(x)
        laurel_x = self.linear_right(laurel_x)
        normed_laurel_x = self.post_laurel_norm(laurel_x)
        return x + normed_laurel_x


class Gemma3nMLP(nn.Module):
    def __init__(
        self,
        hidden_size: int,
        intermediate_size: int,
        hidden_activation: str,
        activation_sparsity: float = 0.0,
238
        quant_config: QuantizationConfig | None = None,
Robert Shaw's avatar
Robert Shaw committed
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
        prefix: str = "",
    ) -> None:
        super().__init__()
        self.gate_up_proj = MergedColumnParallelLinear(
            hidden_size,
            [intermediate_size] * 2,
            bias=False,
            quant_config=quant_config,
            prefix=f"{prefix}.gate_up_proj",
        )
        self.down_proj = RowParallelLinear(
            intermediate_size,
            hidden_size,
            bias=False,
            quant_config=quant_config,
            prefix=f"{prefix}.down_proj",
        )
        if hidden_activation != "gelu_pytorch_tanh":
            raise ValueError(
                "Gemma3 uses `gelu_pytorch_tanh` as the hidden activation "
                "function. Please set `hidden_act` and `hidden_activation` to "
260
261
                "`gelu_pytorch_tanh`."
            )
Robert Shaw's avatar
Robert Shaw committed
262

263
264
265
266
267
268
269
        self.act_fn = (
            GeluAndMulSparse(
                activation_sparsity=activation_sparsity, approximate="tanh"
            )
            if activation_sparsity > 0.0
            else GeluAndMul(approximate="tanh")
        )
Robert Shaw's avatar
Robert Shaw committed
270
271
272
273
274
275
276
277
278

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        gate_up, _ = self.gate_up_proj(x)
        x = self.act_fn(gate_up)
        x, _ = self.down_proj(x)
        return x


class Gemma3nAttention(nn.Module):
279
280
281
282
283
284
285
286
    def __init__(
        self,
        config: Gemma3nTextConfig,
        hidden_size: int,
        num_heads: int,
        num_kv_heads: int,
        head_dim: int,
        max_position_embeddings: int,
287
288
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
289
290
        prefix: str = "",
    ) -> None:
Robert Shaw's avatar
Robert Shaw committed
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
        super().__init__()
        self.config = config
        self.hidden_size = hidden_size
        tp_size = get_tensor_model_parallel_world_size()
        self.total_num_heads = num_heads
        assert self.total_num_heads % tp_size == 0
        self.num_heads = self.total_num_heads // tp_size
        self.total_num_kv_heads = num_kv_heads
        if self.total_num_kv_heads >= tp_size:
            # Number of KV heads is greater than TP size, so we partition
            # the KV heads across multiple tensor parallel GPUs.
            assert self.total_num_kv_heads % tp_size == 0
        else:
            # Number of KV heads is less than TP size, so we replicate
            # the KV heads across multiple tensor parallel GPUs.
            assert tp_size % self.total_num_kv_heads == 0
        self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
        self.head_dim = head_dim
        self.q_size = self.num_heads * self.head_dim
        self.kv_size = self.num_kv_heads * self.head_dim

        self.qkv_proj = QKVParallelLinear(
            hidden_size,
            self.head_dim,
            self.total_num_heads,
            self.total_num_kv_heads,
            bias=config.attention_bias,
            quant_config=quant_config,
            prefix=f"{prefix}.qkv_proj",
        )
        self.o_proj = RowParallelLinear(
            self.total_num_heads * self.head_dim,
            hidden_size,
            bias=config.attention_bias,
            quant_config=quant_config,
            prefix=f"{prefix}.o_proj",
        )
328
329
330
331
332
        self.q_norm = RMSNorm(hidden_size=self.head_dim, eps=config.rms_norm_eps)
        self.k_norm = RMSNorm(hidden_size=self.head_dim, eps=config.rms_norm_eps)
        self.v_norm = RMSNorm(
            hidden_size=self.head_dim, eps=config.rms_norm_eps, has_weight=False
        )
Robert Shaw's avatar
Robert Shaw committed
333
334

        layer_idx = extract_layer_index(prefix)
335
336
        layer_type = config.layer_types[layer_idx]
        is_sliding = layer_type == "sliding_attention"
337
        self.sliding_window = config.sliding_window if is_sliding else None
338

339
        # Initialize the rotary embedding.
340
341
342
        if layer_type in config.rope_parameters:
            # Transformers v5 rope config.
            rope_parameters = config.rope_parameters[layer_type]
Robert Shaw's avatar
Robert Shaw committed
343
        else:
344
            # Transformers v4 rope config.
345
            # Global attention. Use the values in config.json.
346
347
348
349
            rope_parameters = config.rope_parameters.copy()
            # Local attention. Override the values in config.json.
            if is_sliding:
                rope_parameters["rope_theta"] = config.rope_local_base_freq
Robert Shaw's avatar
Robert Shaw committed
350

351
352
353
        first_kv_shared_layer_idx = (
            config.num_hidden_layers - config.num_kv_shared_layers
        )
Robert Shaw's avatar
Robert Shaw committed
354
355
        self.is_kv_shared = layer_idx >= first_kv_shared_layer_idx

Nicolò Lucchesi's avatar
Nicolò Lucchesi committed
356
        kv_sharing_target_layer_name = None
Robert Shaw's avatar
Robert Shaw committed
357
358
359
360
361
        if self.is_kv_shared:
            # Last full attention layer is 1 before sharing
            # Last sliding attention layer is 2 before sharing
            offset = 2 if self.sliding_window is not None else 1
            kv_shared_layer_index = first_kv_shared_layer_idx - offset
Nicolò Lucchesi's avatar
Nicolò Lucchesi committed
362
            if kv_shared_layer_index >= 0:
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
                # Different model wrappers expose layer parameters under
                # different parent attributes.
                # For example:
                #   - Gemma3nForCausalLM → parameters live under "model.layers"
                #   - Gemma3nForConditionalGeneration →
                #     under "language_model.model.layers"
                # This logic extracts the portion of the parameter name
                # *before* ".layers."
                # so downstream code can consistently reference the correct
                # model root regardless of which wrapper class was used.
                if ".layers." in prefix:
                    param_name_before_layers = prefix.split(".layers.")[0]
                else:
                    raise ValueError(
                        "Unexpected prefix format for Gemma3nAttention: "
                        f"'{prefix}'. The prefix is expected to contain "
                        "'.layers.' to correctly determine the KV sharing "
                        "target layer."
                    )
Nicolò Lucchesi's avatar
Nicolò Lucchesi committed
382
                # Only the greater layer is required to specify sharing.
383
                kv_sharing_target_layer_name = f"{param_name_before_layers}.layers.{kv_shared_layer_index}.self_attn.attn"  # noqa: E501
Robert Shaw's avatar
Robert Shaw committed
384
385
386
387
388

        self.rotary_emb = get_rope(
            self.head_dim,
            rotary_dim=self.head_dim,
            max_position=max_position_embeddings,
389
            rope_parameters=rope_parameters,
Robert Shaw's avatar
Robert Shaw committed
390
391
392
393
394
395
396
397
398
399
400
401
            is_neox_style=True,
        )

        self.attn = Attention(
            num_heads=self.num_heads,
            head_size=self.head_dim,
            scale=1.0,
            num_kv_heads=self.num_kv_heads,
            cache_config=cache_config,
            quant_config=quant_config,
            per_layer_sliding_window=self.sliding_window,
            kv_sharing_target_layer_name=kv_sharing_target_layer_name,
402
403
            prefix=f"{prefix}.attn",
        )
Robert Shaw's avatar
Robert Shaw committed
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434

    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
        **kwargs,
    ) -> torch.Tensor:
        qkv, _ = self.qkv_proj(hidden_states)
        q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)

        q = q.unflatten(-1, (self.num_heads, self.head_dim))
        q = self.q_norm(q)
        q = q.flatten(-2, -1)
        k = k.unflatten(-1, (self.num_kv_heads, self.head_dim))
        k = self.k_norm(k)
        k = k.flatten(-2, -1)
        v = v.unflatten(-1, (self.num_kv_heads, self.head_dim))
        v = self.v_norm(v)
        v = v.flatten(-2, -1)

        q, k = self.rotary_emb(positions, q, k)
        attn_output = self.attn(q, k, v)

        output, _ = self.o_proj(attn_output)
        return output


class Gemma3nDecoderLayer(nn.Module):
    def __init__(
        self,
        config: Gemma3nTextConfig,
435
436
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
Robert Shaw's avatar
Robert Shaw committed
437
438
439
        prefix: str = "",
    ) -> None:
        super().__init__()
Nicolò Lucchesi's avatar
Nicolò Lucchesi committed
440
        assert isinstance(config, Gemma3nTextConfig)
Robert Shaw's avatar
Robert Shaw committed
441
442
443
444
445
446
447
448
449
        self.altup_active_idx = config.altup_active_idx
        assert config.altup_correct_scale

        self.altup = Gemma3nAltUp(
            hidden_size=config.hidden_size,
            rms_norm_eps=config.rms_norm_eps,
            altup_num_inputs=config.altup_num_inputs,
            altup_coef_clip=config.altup_coef_clip,
            altup_active_idx=config.altup_active_idx,
450
            quant_config=quant_config,
Robert Shaw's avatar
Robert Shaw committed
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
            prefix=f"{prefix}.altup",
        )
        self.self_attn = Gemma3nAttention(
            config=config,
            hidden_size=config.hidden_size,
            num_heads=config.num_attention_heads,
            num_kv_heads=config.num_key_value_heads,
            head_dim=config.head_dim,
            max_position_embeddings=config.max_position_embeddings,
            cache_config=cache_config,
            quant_config=quant_config,
            prefix=f"{prefix}.self_attn",
        )
        self.mlp = Gemma3nMLP(
            hidden_size=config.hidden_size,
            # NOTE: Matformer https://github.com/huggingface/transformers/blob/a52478253bbe522a420e88ea3940d4d98a935300/src/transformers/models/gemma3n/modular_gemma3n.py#L258 # noqa: E501
467
            intermediate_size=config.intermediate_size[extract_layer_index(prefix)],
Robert Shaw's avatar
Robert Shaw committed
468
469
470
            hidden_activation=config.hidden_activation,
            quant_config=quant_config,
            activation_sparsity=config.activation_sparsity_pattern[
471
472
                extract_layer_index(prefix)
            ],
Robert Shaw's avatar
Robert Shaw committed
473
474
475
476
477
478
            prefix=f"{prefix}.mlp",
        )
        self.laurel = Gemma3nLaurelBlock(
            hidden_size=config.hidden_size,
            laurel_rank=config.laurel_rank,
            rms_norm_eps=config.rms_norm_eps,
479
            quant_config=quant_config,
Robert Shaw's avatar
Robert Shaw committed
480
481
482
483
484
485
486
487
488
489
            prefix=f"{prefix}.laurel",
        )

        # NOTE(rob): should be ColumnParallelLinear and RowParallelLinear
        # But, we need to add per_layer_input_gate(x) to per_layer_input.
        # per_layer_input cannot be sharded, so we replicate for now.
        self.per_layer_input_gate = ReplicatedLinear(
            config.hidden_size,
            config.hidden_size_per_layer_input,
            bias=False,
490
            quant_config=quant_config,
Robert Shaw's avatar
Robert Shaw committed
491
492
493
494
495
496
497
            prefix=f"{prefix}.per_layer_input_gate",
            return_bias=False,
        )
        self.per_layer_projection = ReplicatedLinear(
            config.hidden_size_per_layer_input,
            config.hidden_size,
            bias=False,
498
            quant_config=quant_config,
Robert Shaw's avatar
Robert Shaw committed
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
            prefix=f"{prefix}.per_layer_projection",
            return_bias=False,
        )

        # LayerNorms.
        self.input_layernorm = RMSNorm(
            config.hidden_size,
            eps=config.rms_norm_eps,
        )
        self.post_attention_layernorm = RMSNorm(
            config.hidden_size,
            eps=config.rms_norm_eps,
        )
        self.pre_feedforward_layernorm = RMSNorm(
            config.hidden_size,
            eps=config.rms_norm_eps,
        )
        self.post_feedforward_layernorm = RMSNorm(
            config.hidden_size,
            eps=config.rms_norm_eps,
        )
        self.post_per_layer_input_norm = RMSNorm(
            config.hidden_size,
            eps=config.rms_norm_eps,
        )

        self.act_fn = _ACTIVATION_REGISTRY[config.hidden_activation]

    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
        per_layer_input: torch.Tensor,
        **kwargs,
    ) -> tuple[torch.Tensor, torch.Tensor]:
        # ActUp (predict).
        predictions = self.altup.predict(hidden_states)
        active_prediction = predictions[self.altup_active_idx]
        active_prediction_normed = self.input_layernorm(active_prediction)
        laurel_output = self.laurel(active_prediction_normed)

        # Attention.
        attn = self.self_attn(
            positions=positions,
            hidden_states=active_prediction_normed,
            **kwargs,
        )
        attn = self.post_attention_layernorm(attn)
        attn_gated = attn + active_prediction
548
        attn_laurel = (attn_gated + laurel_output) / torch.sqrt(torch.tensor(2.0))
Robert Shaw's avatar
Robert Shaw committed
549
550
551
552
553
554
555
556

        # MLP.
        attn_norm = self.pre_feedforward_layernorm(attn_laurel)
        attn_ffw = self.mlp(attn_norm)
        attn_ffw_norm = self.post_feedforward_layernorm(attn_ffw)
        attn_ffw_laurel_gated = attn_laurel + attn_ffw_norm

        # ActUp (connect).
557
        corrected_predictions = self.altup.correct(predictions, attn_ffw_laurel_gated)
Robert Shaw's avatar
Robert Shaw committed
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
        first_prediction = corrected_predictions[self.altup_active_idx]
        first_prediction = self.altup.scale_corrected_output(first_prediction)

        # per_layer_input_gate adapted from jax.numpy.einsum("btd,dp->btp", ...)
        first_prediction = self.per_layer_input_gate(first_prediction)
        first_prediction = self.act_fn(first_prediction)
        first_prediction = torch.mul(first_prediction, per_layer_input)

        # per_layer_projection adapted from jax.numpy.einsum("btp,pd->btd", ...)
        first_prediction = self.per_layer_projection(first_prediction)
        first_prediction = self.post_per_layer_input_norm(first_prediction)
        corrected_predictions[1:] += first_prediction

        return corrected_predictions


574
# This enables torch.compile if --kv-sharing-fast-prefill passed
575
576
577
@support_torch_compile(
    enable_if=lambda vllm_config: vllm_config.cache_config.kv_sharing_fast_prefill
)
578
579
580
581
class Gemma3nSelfDecoder(nn.Module):
    """
    Includes altup embedding and self decoder layers
    """
Robert Shaw's avatar
Robert Shaw committed
582

583
584
585
586
587
588
589
590
    def __init__(
        self,
        *,
        vllm_config: VllmConfig,
        prefix: str = "",
        decoder_layers: list[Gemma3nDecoderLayer],
        layer_idx_start: int,
    ):
Robert Shaw's avatar
Robert Shaw committed
591
        super().__init__()
592
593
594
        self.decoder_layers = decoder_layers
        self.layer_idx_start = layer_idx_start

Nicolò Lucchesi's avatar
Nicolò Lucchesi committed
595
        config = vllm_config.model_config.hf_config
Robert Shaw's avatar
Robert Shaw committed
596
        self.config = config
597
        quant_config = vllm_config.quant_config
598

Robert Shaw's avatar
Robert Shaw committed
599
600
601
        self.embed_tokens = VocabParallelEmbedding(
            config.vocab_size,
            config.hidden_size,
602
            quant_config=quant_config,
Robert Shaw's avatar
Robert Shaw committed
603
604
605
606
607
608
            prefix=f"{prefix}.embed_tokens",
        )
        self.embed_scale = torch.tensor(
            config.hidden_size**0.5,
            dtype=self.embed_tokens.weight.dtype,
        )
Nicolò Lucchesi's avatar
Nicolò Lucchesi committed
609
        # Additional per-layer embeddings (PLE)
Robert Shaw's avatar
Robert Shaw committed
610
611
612
        self.embed_tokens_per_layer = VocabParallelEmbedding(
            config.vocab_size_per_layer_input,
            config.num_hidden_layers * config.hidden_size_per_layer_input,
613
            quant_config=quant_config,
Robert Shaw's avatar
Robert Shaw committed
614
615
616
617
618
619
620
621
622
623
624
625
            prefix=f"{prefix}.per_layer_embed_tokens",
        )
        self.embed_scale_per_layer = torch.tensor(
            config.hidden_size_per_layer_input**0.5,
            dtype=self.embed_tokens.weight.dtype,
        )
        self.per_layer_model_projection = ColumnParallelLinear(
            config.hidden_size,
            config.num_hidden_layers * config.hidden_size_per_layer_input,
            bias=False,
            gather_output=True,
            return_bias=False,
626
            quant_config=quant_config,
Robert Shaw's avatar
Robert Shaw committed
627
628
629
630
631
632
633
            prefix=f"{prefix}.per_layer_model_projection",
        )
        self.per_layer_projection_norm = RMSNorm(
            hidden_size=config.hidden_size_per_layer_input,
            eps=config.rms_norm_eps,
        )
        self.per_layer_input_scale = torch.rsqrt(torch.tensor(2.0)).to(
634
635
            self.embed_tokens.weight.dtype
        )
Robert Shaw's avatar
Robert Shaw committed
636
637
638
639
        self.per_layer_projection_scale = torch.tensor(
            config.hidden_size**0.5,
            dtype=self.embed_tokens.weight.dtype,
        )
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
        self.altup_projections = nn.ModuleList(
            [
                ColumnParallelLinear(
                    config.hidden_size,
                    config.hidden_size,
                    bias=False,
                    gather_output=True,
                    return_bias=False,
                    quant_config=quant_config,
                    prefix=f"{prefix}.altup_projections.{idx - 1}",
                )
                for idx in range(1, self.config.altup_num_inputs)
            ]
        )

    def get_per_layer_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
656
657
658
659
        # Deal with the fact that vocab_size_per_layer_input < vocab_size
        # which causes us to have some out of vocab tokens by setting
        # those token ids to 0. This matches the HF implementation.
        per_layer_inputs_mask = torch.logical_and(
660
661
662
663
664
665
666
667
668
            input_ids >= 0, input_ids < self.config.vocab_size_per_layer_input
        )
        per_layer_inputs_tokens = torch.where(
            per_layer_inputs_mask, input_ids, torch.zeros_like(input_ids)
        )
        return (
            self.embed_tokens_per_layer(per_layer_inputs_tokens)
            * self.embed_scale_per_layer
        )
669

670
    def get_per_layer_inputs(
Robert Shaw's avatar
Robert Shaw committed
671
        self,
672
        hidden_states_0: torch.Tensor,
673
        per_layer_inputs: torch.Tensor | None,
674
    ) -> torch.Tensor:
675
676
677
678
679
        per_layer_projection = self.per_layer_model_projection(hidden_states_0)
        per_layer_projection = per_layer_projection.reshape(
            *hidden_states_0.shape[:-1],
            self.config.num_hidden_layers,
            self.config.hidden_size_per_layer_input,
Robert Shaw's avatar
Robert Shaw committed
680
        )
681
        per_layer_projection = self.per_layer_projection_norm(per_layer_projection)
682
683
684
685
        if per_layer_inputs is not None:
            # Profiling run does not compute per_layer_inputs
            per_layer_inputs = per_layer_projection + per_layer_inputs
            per_layer_inputs *= self.per_layer_input_scale
Nicolò Lucchesi's avatar
Nicolò Lucchesi committed
686
        else:
687
            per_layer_inputs = per_layer_projection
688
689
        return per_layer_inputs

690
    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
691
        return self.embed_tokens(input_ids) * self.embed_scale
Robert Shaw's avatar
Robert Shaw committed
692

693
    def altup_embed(self, hidden_states_0: torch.Tensor) -> torch.Tensor:
694
695
        # Altup embed.
        hidden_states = [hidden_states_0] * self.config.altup_num_inputs
696
        target_magnitude = torch.mean(hidden_states_0**2, dim=-1, keepdim=True) ** 0.5
697
698
        for i in range(1, self.config.altup_num_inputs):
            hidden_states[i] = self.altup_projections[i - 1](hidden_states[i])
699
700
701
702
            new_magnitude = (
                torch.mean(hidden_states[i] ** 2, dim=-1, keepdim=True) ** 0.5
            )
            hidden_states[i] *= target_magnitude / torch.maximum(new_magnitude, EPS)
703
704
705
706
707
708
709
        hidden_states = torch.stack(hidden_states, dim=-1)
        return hidden_states

    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
710
711
        inputs_embeds: torch.Tensor | None = None,
        per_layer_inputs: torch.Tensor | None = None,
712
713
714
715
716
        **kwargs,
    ) -> tuple[torch.Tensor, torch.Tensor]:
        if inputs_embeds is not None:
            hidden_states_0 = inputs_embeds
        else:
717
            hidden_states_0 = self.embed_input_ids(input_ids)
718
719

        adjusted_per_layer_inputs = self.get_per_layer_inputs(
720
721
            hidden_states_0, per_layer_inputs
        )
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
        hidden_states = self.altup_embed(hidden_states_0)

        # [altnum_inputs, num_tokens, hidden_size]
        hidden_states = hidden_states.permute(2, 0, 1)

        for idx, layer in enumerate(self.decoder_layers):
            layer_idx = idx + self.layer_idx_start
            # [altup_num_inputs, num_tokens, hidden_size]
            hidden_states = layer(
                positions=positions,
                hidden_states=hidden_states,
                per_layer_input=adjusted_per_layer_inputs[:, layer_idx, :],
                **kwargs,
            )

        # [num_tokens, hidden_size, altnum_inputs]
        hidden_states = hidden_states.permute(1, 2, 0)

        return hidden_states, adjusted_per_layer_inputs


# This enables torch.compile if --kv-sharing-fast-prefill passed
744
745
746
@support_torch_compile(
    enable_if=lambda vllm_config: vllm_config.cache_config.kv_sharing_fast_prefill
)
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
class Gemma3nCrossDecoder(nn.Module):
    """
    Cross-decoder layers
    """

    def __init__(
        self,
        *,
        vllm_config: VllmConfig,
        prefix: str = "",
        decoder_layers: list[Gemma3nDecoderLayer],
        layer_idx_start: int,
    ):
        super().__init__()
        self.decoder_layers = decoder_layers
        self.layer_idx_start = layer_idx_start
Robert Shaw's avatar
Robert Shaw committed
763

764
765
766
767
768
769
770
771
772
773
774
    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
        per_layer_inputs: torch.Tensor,
        **kwargs,
    ) -> torch.Tensor:
        # [altnum_inputs, num_tokens, hidden_size]
        hidden_states = hidden_states.permute(2, 0, 1)
        for idx, layer in enumerate(self.decoder_layers):
            layer_idx = idx + self.layer_idx_start
775
776
777
778
779
780
781
            # [altup_num_inputs, num_tokens, hidden_size]
            hidden_states = layer(
                positions=positions,
                hidden_states=hidden_states,
                per_layer_input=per_layer_inputs[:, layer_idx, :],
                **kwargs,
            )
782
783
784
        # [num_tokens, hidden_size, altnum_inputs]
        hidden_states = hidden_states.permute(1, 2, 0)
        return hidden_states
Robert Shaw's avatar
Robert Shaw committed
785

786
787

# This disables torch.compile if --kv-sharing-fast-prefill passed
788
789
790
@support_torch_compile(
    enable_if=lambda vllm_config: not vllm_config.cache_config.kv_sharing_fast_prefill
)
791
792
793
794
795
796
797
798
799
class Gemma3nTextModel(nn.Module, SupportsQuant):
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__()
        config = vllm_config.model_config.hf_config
        cache_config = vllm_config.cache_config
        quant_config = vllm_config.quant_config
        self.config = config
        self.quant_config = quant_config

800
801
802
803
804
805
806
807
808
809
810
811
812
813
        self.altup_unembed_projections = nn.ModuleList(
            [
                ColumnParallelLinear(
                    config.hidden_size,
                    config.hidden_size,
                    bias=False,
                    gather_output=True,
                    return_bias=False,
                    quant_config=quant_config,
                    prefix=f"{prefix}.altup_unembed_projections.{idx - 1}",
                )
                for idx in range(1, self.config.altup_num_inputs)
            ]
        )
814
815
816
817
818

        # Allocate config.num_kv_shared_layers layers for self-decoder
        self.start_layer, self.end_layer, self.layers = make_layers(
            config.num_hidden_layers,
            lambda prefix: Gemma3nDecoderLayer(
819
820
821
822
                config, cache_config, quant_config, prefix=prefix
            ),
            prefix=f"{prefix}.layers",
        )
823

824
825
826
        first_kv_shared_layer_idx = (
            config.num_hidden_layers - config.num_kv_shared_layers
        )
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860

        # NOTE(sarckk): importing this top level seems to cause issues
        # during running of tests.
        from vllm.compilation.backends import set_model_tag

        # Layer idx 0-19 are self-decoder layers in You Only Cache Once (YOCO)
        with set_model_tag("self_decoder"):
            self.self_decoder = Gemma3nSelfDecoder(
                vllm_config=vllm_config,
                prefix=f"{prefix}.self_decoder",
                decoder_layers=self.layers[:first_kv_shared_layer_idx],
                layer_idx_start=0,
            )
        # Layer idx 20-30 are cross-decoder layers in YOCO
        with set_model_tag("cross_decoder"):
            self.cross_decoder = Gemma3nCrossDecoder(
                vllm_config=vllm_config,
                prefix=f"{prefix}.cross_decoder",
                decoder_layers=self.layers[first_kv_shared_layer_idx:],
                layer_idx_start=first_kv_shared_layer_idx,
            )

        self.norm = RMSNorm(
            config.hidden_size,
            eps=config.rms_norm_eps,
        )

        self.fast_prefill_enabled = cache_config.kv_sharing_fast_prefill

        if self.fast_prefill_enabled:
            # Allocate static buffers for CUDAGraph
            # TODO(sarckk): Extract this functionality to interface
            max_num_tokens = vllm_config.scheduler_config.max_num_batched_tokens
            device = next(self.parameters()).device
861
862
863
            self.positions = torch.zeros(
                max_num_tokens, dtype=torch.int64, device=device
            )
864
            self.hidden_states = torch.zeros(
865
                (max_num_tokens, config.hidden_size, self.config.altup_num_inputs),
866
867
868
869
                dtype=self.embed_tokens.weight.dtype,
                device=device,
            )
            self.per_layer_inputs = torch.zeros(
870
871
872
873
874
                (
                    max_num_tokens,
                    self.config.num_hidden_layers,
                    self.config.hidden_size_per_layer_input,
                ),
875
876
877
878
879
880
881
882
                dtype=self.embed_tokens.weight.dtype,
                device=device,
            )

    @property
    def embed_tokens(self):
        return self.self_decoder.embed_tokens

883
    def get_per_layer_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
884
885
        return self.self_decoder.get_per_layer_input_embeddings(input_ids)

886
887
    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.self_decoder.embed_input_ids(input_ids)
888
889
890
891
892

    def fast_prefill_forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
893
894
        inputs_embeds: torch.Tensor | None = None,
        per_layer_inputs: torch.Tensor | None = None,
895
896
897
898
899
900
        **kwargs,
    ) -> torch.Tensor:
        logits_indices_padded, num_logits_indices = None, None
        attn_metadata = get_forward_context().attn_metadata

        # attn_metadata is None during dummy runs
901
        if self.fast_prefill_enabled and attn_metadata is not None:
902
903
904
            assert isinstance(attn_metadata, dict)
            # Last layer is a KV sharing layer
            layer_attn_metadata = attn_metadata[
905
906
907
908
                self.layers[-1].self_attn.attn.layer_name
            ]
            if isinstance(layer_attn_metadata, KVSharingFastPrefillMetadata):
                logits_indices_padded = layer_attn_metadata.logits_indices_padded
909
910
911
912
913
                num_logits_indices = layer_attn_metadata.num_logits_indices

        # Copy inputs for cudagraph
        batch_size = positions.size(0)
        self.positions[:batch_size].copy_(positions)
914
915
916
917
918
919
920
        self_decoder_hidden_states, per_layer_inputs_adjusted = self.self_decoder(
            input_ids=input_ids,
            positions=self.positions[:batch_size],
            inputs_embeds=inputs_embeds,
            per_layer_inputs=per_layer_inputs,
            **kwargs,
        )
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939

        if logits_indices_padded is None:
            logits_indices_padded = torch.arange(
                positions.size(0),
                dtype=positions.dtype,
                device=positions.device,
            )

        # NOTE(sarckk): There is currently a bug caused by
        # vLLM converting output of last piecewise CUDA graph
        # to weakref, causing memory to be prematurely freed
        # when there are multiple compilation units
        # Keep .clone() until fix in
        # https://github.com/vllm-project/vllm/pull/22282
        hidden_states = self_decoder_hidden_states.clone()

        # Copy inputs for cudagraph
        num_padded_logits_indices = logits_indices_padded.size(0)
        self.positions[:num_padded_logits_indices].copy_(
940
941
            positions[logits_indices_padded]
        )
942
        self.hidden_states[:num_padded_logits_indices].copy_(
943
944
            self_decoder_hidden_states[logits_indices_padded]
        )
945
        self.per_layer_inputs[:num_padded_logits_indices].copy_(
946
947
            per_layer_inputs_adjusted[logits_indices_padded]
        )
948
949
950
951
952
953
954
955
956
957
958
        cross_decoder_hidden_states = self.cross_decoder(
            positions=self.positions[:num_padded_logits_indices],
            hidden_states=self.hidden_states[:num_padded_logits_indices],
            per_layer_inputs=self.per_layer_inputs[:num_padded_logits_indices],
            **kwargs,
        )

        if num_logits_indices is not None:
            assert num_logits_indices > 0
            # Merge cross-decoder and self-decoder hidden states
            hidden_states[logits_indices_padded[:num_logits_indices]] = (
959
960
                cross_decoder_hidden_states[:num_logits_indices]
            )
961
962
963
964
965
966
967
968
969
        else:
            hidden_states = cross_decoder_hidden_states

        return hidden_states

    def normal_forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
970
971
        inputs_embeds: torch.Tensor | None = None,
        per_layer_inputs: torch.Tensor | None = None,
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
        **kwargs,
    ) -> torch.Tensor:
        hidden_states, per_layer_inputs = self.self_decoder(
            input_ids=input_ids,
            positions=positions,
            inputs_embeds=inputs_embeds,
            per_layer_inputs=per_layer_inputs,
            **kwargs,
        )
        hidden_states = self.cross_decoder(
            positions=positions,
            hidden_states=hidden_states,
            per_layer_inputs=per_layer_inputs,
            **kwargs,
        )
        return hidden_states

    def altup_unembed(
        self,
        hidden_states: torch.Tensor,
    ) -> torch.Tensor:
Robert Shaw's avatar
Robert Shaw committed
993
        # Altup unembed.
994
995
996
        target_magnitude = (
            torch.mean(hidden_states[..., 0] ** 2, dim=-1, keepdim=True) ** 0.5
        )
Robert Shaw's avatar
Robert Shaw committed
997
        for i in range(1, self.config.altup_num_inputs):
998
            hidden_states[..., i] = self.altup_unembed_projections[i - 1](
999
1000
1001
1002
1003
                hidden_states[..., i]
            )
            new_magnitude = (
                torch.mean(hidden_states[..., i] ** 2, dim=-1, keepdim=True) ** 0.5
            )
1004
            hidden_states[..., i] *= target_magnitude / torch.maximum(
1005
1006
                new_magnitude, EPS
            )
1007
1008
1009
        # [num_tokens,hidden_size, altup_num_inputs] -> [num_tokens,hidden_size]
        hidden_states = torch.mean(hidden_states, dim=-1)
        return hidden_states
Robert Shaw's avatar
Robert Shaw committed
1010

1011
1012
    def forward(
        self,
1013
        input_ids: torch.Tensor | None,
1014
        positions: torch.Tensor,
1015
1016
1017
        per_layer_inputs: torch.Tensor | None = None,
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
1018
        **kwargs,
1019
    ) -> torch.Tensor | IntermediateTensors:
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
        if self.fast_prefill_enabled:
            hidden_states = self.fast_prefill_forward(
                input_ids,
                positions,
                inputs_embeds,
                per_layer_inputs,
                **kwargs,
            )
        else:
            hidden_states = self.normal_forward(
                input_ids,
                positions,
                inputs_embeds,
                per_layer_inputs,
                **kwargs,
            )
        hidden_states = self.altup_unembed(hidden_states)
Robert Shaw's avatar
Robert Shaw committed
1037
1038
        return self.norm(hidden_states)

1039
    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
Robert Shaw's avatar
Robert Shaw committed
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
        stacked_params_mapping = [
            # (param_name, shard_name, shard_id)
            ("qkv_proj", "q_proj", "q"),
            ("qkv_proj", "k_proj", "k"),
            ("qkv_proj", "v_proj", "v"),
            ("gate_up_proj", "gate_proj", 0),
            ("gate_up_proj", "up_proj", 1),
        ]
        params_dict = dict(self.named_parameters())
        loaded_params: set[str] = set()
        for name, loaded_weight in weights:
1051
1052
            # decoder layer weights, altup_unembed_projections and rmsnorm
            # are initialized in text model, others are in self decoder
1053
1054
1055
1056
1057
            if (
                not name.startswith("layers")
                and not name.startswith("altup_unembed_projections")
                and not name.startswith("norm")
            ):
1058
1059
                name = f"self_decoder.{name}"

1060
1061
1062
            if self.quant_config is not None and (
                scale_name := self.quant_config.get_cache_scale(name)
            ):
Robert Shaw's avatar
Robert Shaw committed
1063
1064
                # Loading kv cache scales for compressed-tensors quantization
                param = params_dict[scale_name]
1065
                weight_loader = getattr(param, "weight_loader", default_weight_loader)
Robert Shaw's avatar
Robert Shaw committed
1066
1067
1068
1069
                loaded_weight = loaded_weight[0]
                weight_loader(param, loaded_weight)
                loaded_params.add(scale_name)
                continue
1070
            for param_name, shard_name, shard_id in stacked_params_mapping:
Robert Shaw's avatar
Robert Shaw committed
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
                if shard_name not in name:
                    continue
                # Avoid spurious match with ".up_proj".
                if "altup_projections" in name:
                    continue
                name = name.replace(shard_name, param_name)
                # Skip loading extra bias for GPTQ models.
                if name.endswith(".bias") and name not in params_dict:
                    continue
                if is_pp_missing_parameter(name, self):
                    continue
                param = params_dict[name]
                weight_loader = param.weight_loader
                weight_loader(param, loaded_weight, shard_id)
                break
            else:
                # Skip loading extra bias for GPTQ models.
                if name.endswith(".bias") and name not in params_dict:
                    continue
                # Remapping the name of FP8 kv-scale.
                name = maybe_remap_kv_scale_name(name, params_dict)
                if name is None:
                    continue
                if is_pp_missing_parameter(name, self):
                    continue
                param = params_dict[name]
1097
                weight_loader = getattr(param, "weight_loader", default_weight_loader)
Robert Shaw's avatar
Robert Shaw committed
1098
1099
1100
1101
1102
1103
                weight_loader(param, loaded_weight)
            loaded_params.add(name)

        return loaded_params


Nicolò Lucchesi's avatar
Nicolò Lucchesi committed
1104
class Gemma3nForCausalLM(nn.Module):
Robert Shaw's avatar
Robert Shaw committed
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
    packed_modules_mapping = {
        "qkv_proj": [
            "q_proj",
            "k_proj",
            "v_proj",
        ],
        "gate_up_proj": [
            "gate_proj",
            "up_proj",
        ],
    }

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        config = vllm_config.model_config.hf_config
1119

Robert Shaw's avatar
Robert Shaw committed
1120
1121
        super().__init__()
        self.config = config
1122
        self.cache_config = vllm_config.cache_config
1123
1124
1125
        self.model = Gemma3nTextModel(
            vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
        )
Robert Shaw's avatar
Robert Shaw committed
1126
        self.logits_processor = LogitsProcessor(
1127
1128
            config.vocab_size, soft_cap=config.final_logit_softcapping
        )
Robert Shaw's avatar
Robert Shaw committed
1129

1130
1131
    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.model.embed_input_ids(input_ids)
Robert Shaw's avatar
Robert Shaw committed
1132
1133
1134
1135
1136

    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
Nicolò Lucchesi's avatar
Nicolò Lucchesi committed
1137
        *,
1138
1139
1140
        per_layer_inputs: torch.Tensor | None = None,
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
Robert Shaw's avatar
Robert Shaw committed
1141
        **kwargs,
1142
    ) -> torch.Tensor | IntermediateTensors:
Nicolò Lucchesi's avatar
Nicolò Lucchesi committed
1143
1144
1145
1146
1147
1148
1149
1150
        hidden_states = self.model(
            input_ids,
            positions,
            per_layer_inputs=per_layer_inputs,
            intermediate_tensors=intermediate_tensors,
            inputs_embeds=inputs_embeds,
            **kwargs,
        )
Robert Shaw's avatar
Robert Shaw committed
1151
1152
1153
1154
1155
        return hidden_states

    def compute_logits(
        self,
        hidden_states: torch.Tensor,
1156
    ) -> torch.Tensor | None:
1157
        logits = self.logits_processor(self.model.embed_tokens, hidden_states)
Robert Shaw's avatar
Robert Shaw committed
1158
1159
        return logits

1160
1161
1162
1163
1164
1165
1166
    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
        loader = AutoWeightsLoader(
            self,
            skip_substrs=(
                ["embed_audio.", "embed_vision.", "audio_tower.", "vision_tower."]
            ),
        )
Robert Shaw's avatar
Robert Shaw committed
1167
        return loader.load_weights(weights)