|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +"""Load a GGUF file into a Gemma 4 31B model. |
| 8 | +
|
| 9 | +Streams tensors one at a time via ``iter_gguf_tensors`` for low peak |
| 10 | +memory, remaps GGUF names to model FQNs, handles tied embed/lm_head, |
| 11 | +and packs for the target backend. |
| 12 | +
|
| 13 | +Usage: |
| 14 | + model, config = load_gguf_model("model.gguf", backend="cuda") |
| 15 | +""" |
| 16 | + |
| 17 | +from typing import Optional |
| 18 | + |
| 19 | +import torch |
| 20 | + |
| 21 | +# GGUF pattern → model FQN pattern. ``{}`` is the layer index. |
| 22 | +_KEY_MAP = { |
| 23 | + "token_embd.weight": "embed_tokens.weight", |
| 24 | + "output_norm.weight": "norm.weight", |
| 25 | + # Per-layer attention |
| 26 | + "blk.{}.attn_q.weight": "layers.{}.self_attn.q_proj.weight", |
| 27 | + "blk.{}.attn_k.weight": "layers.{}.self_attn.k_proj.weight", |
| 28 | + "blk.{}.attn_v.weight": "layers.{}.self_attn.v_proj.weight", |
| 29 | + "blk.{}.attn_output.weight": "layers.{}.self_attn.o_proj.weight", |
| 30 | + "blk.{}.attn_q_norm.weight": "layers.{}.self_attn.q_norm.weight", |
| 31 | + "blk.{}.attn_k_norm.weight": "layers.{}.self_attn.k_norm.weight", |
| 32 | + # Per-layer norms |
| 33 | + "blk.{}.attn_norm.weight": "layers.{}.input_layernorm.weight", |
| 34 | + "blk.{}.post_attention_norm.weight": "layers.{}.post_attention_layernorm.weight", |
| 35 | + "blk.{}.ffn_norm.weight": "layers.{}.pre_feedforward_layernorm.weight", |
| 36 | + "blk.{}.post_ffw_norm.weight": "layers.{}.post_feedforward_layernorm.weight", |
| 37 | + # Per-layer MLP |
| 38 | + "blk.{}.ffn_gate.weight": "layers.{}.mlp.gate_proj.weight", |
| 39 | + "blk.{}.ffn_up.weight": "layers.{}.mlp.up_proj.weight", |
| 40 | + "blk.{}.ffn_down.weight": "layers.{}.mlp.down_proj.weight", |
| 41 | + # Per-layer scalar |
| 42 | + "blk.{}.layer_output_scale.weight": "layers.{}.layer_scalar", |
| 43 | +} |
| 44 | + |
| 45 | +_IGNORED_KEYS = {"rope_freqs.weight"} |
| 46 | + |
| 47 | + |
| 48 | +def gguf_to_model_key(gguf_key: str) -> Optional[str]: |
| 49 | + """Map a GGUF tensor name to a model FQN, or ``None`` to skip.""" |
| 50 | + if gguf_key in _IGNORED_KEYS: |
| 51 | + return None |
| 52 | + |
| 53 | + for gguf_pat, model_pat in _KEY_MAP.items(): |
| 54 | + if "{}" not in gguf_pat: |
| 55 | + if gguf_key == gguf_pat: |
| 56 | + return model_pat |
| 57 | + continue |
| 58 | + prefix, suffix = gguf_pat.split("{}") |
| 59 | + if gguf_key.startswith(prefix) and gguf_key.endswith(suffix): |
| 60 | + layer_str = gguf_key[len(prefix) : len(gguf_key) - len(suffix)] |
| 61 | + if layer_str.isdigit(): |
| 62 | + return model_pat.replace("{}", layer_str) |
| 63 | + |
| 64 | + return None |
| 65 | + |
| 66 | + |
| 67 | +def _resolve_tied_lm_head(model, embed_cw, packers): |
| 68 | + """Handle tied embed/lm_head after streaming all tensors.""" |
| 69 | + from executorch.examples.models.gemma4_31b.quant import pack_one |
| 70 | + |
| 71 | + lm_head = getattr(model.lm_head, "weight", None) |
| 72 | + if lm_head is None or lm_head.device.type != "meta": |
| 73 | + return |
| 74 | + if embed_cw is not None: |
| 75 | + pack_one(model, "lm_head.weight", embed_cw, packers) |
| 76 | + else: |
| 77 | + pack_one( |
| 78 | + model, |
| 79 | + "lm_head.weight", |
| 80 | + model.embed_tokens.weight.data.clone(), |
| 81 | + packers, |
| 82 | + ) |
| 83 | + |
| 84 | + |
| 85 | +def _validate_no_meta(model): |
| 86 | + """Ensure all parameters have been loaded.""" |
| 87 | + for fqn, p in model.named_parameters(): |
| 88 | + if p.device.type == "meta": |
| 89 | + raise RuntimeError( |
| 90 | + f"Weight '{fqn}' not found in GGUF file " |
| 91 | + f"(model/checkpoint version mismatch?)" |
| 92 | + ) |
| 93 | + for p in model.parameters(): |
| 94 | + p.requires_grad_(False) |
| 95 | + |
| 96 | + |
| 97 | +def load_gguf_model( |
| 98 | + gguf_path: str, |
| 99 | + max_seq_len: int = 4096, |
| 100 | + backend: str = "cuda", |
| 101 | +) -> tuple: |
| 102 | + """Load a GGUF file, remap keys, and pack for the target backend. |
| 103 | +
|
| 104 | + Streams tensors one at a time for low peak memory. |
| 105 | +
|
| 106 | + GGUF ties ``embed_tokens`` and ``lm_head`` into a single Q4_K tensor. |
| 107 | + We untie them: the embedding is dequantized to bf16 (``nn.Embedding`` |
| 108 | + needs gather, which ``Int4TilePackedTo4dTensor`` does not support), |
| 109 | + while ``lm_head`` keeps the original Q4_K quantization (``nn.Linear`` |
| 110 | + matmul via tinygemm). |
| 111 | +
|
| 112 | + Returns ``(model, config)``. |
| 113 | + """ |
| 114 | + from executorch.examples.models.gemma4_31b.model import Gemma4_31B, Gemma4_31BConfig |
| 115 | + from executorch.examples.models.gemma4_31b.quant import dequantize_weight, pack_one |
| 116 | + from executorch.examples.models.gemma4_31b.quant.gguf import iter_gguf_tensors |
| 117 | + from executorch.examples.models.gemma4_31b.quant.serialize import ( |
| 118 | + CanonicalQuantizedWeight, |
| 119 | + ) |
| 120 | + |
| 121 | + if backend == "cuda": |
| 122 | + from executorch.examples.models.gemma4_31b.quant import DEFAULT_CUDA_PACKERS |
| 123 | + |
| 124 | + packers = DEFAULT_CUDA_PACKERS |
| 125 | + else: |
| 126 | + raise ValueError(f"Unsupported backend: {backend!r}. Supported: 'cuda'.") |
| 127 | + |
| 128 | + config = Gemma4_31BConfig(max_seq_len=max_seq_len) |
| 129 | + |
| 130 | + print("Building model on meta device...") |
| 131 | + with torch.device("meta"): |
| 132 | + model = Gemma4_31B(config) |
| 133 | + |
| 134 | + embed_cw = None |
| 135 | + n_processed = 0 |
| 136 | + |
| 137 | + print(f"Streaming GGUF from {gguf_path}...") |
| 138 | + for gguf_name, result in iter_gguf_tensors(gguf_path): |
| 139 | + model_key = gguf_to_model_key(gguf_name) |
| 140 | + if model_key is None: |
| 141 | + continue |
| 142 | + |
| 143 | + if isinstance(result, torch.Tensor) and result.dtype == torch.float32: |
| 144 | + result = result.to(torch.bfloat16) |
| 145 | + |
| 146 | + if model_key == "embed_tokens.weight" and isinstance( |
| 147 | + result, CanonicalQuantizedWeight |
| 148 | + ): |
| 149 | + embed_cw = result |
| 150 | + result = dequantize_weight(result, torch.bfloat16) |
| 151 | + |
| 152 | + pack_one(model, model_key, result, packers) |
| 153 | + |
| 154 | + n_processed += 1 |
| 155 | + if n_processed % 100 == 0: |
| 156 | + print(f" Processed {n_processed} tensors...") |
| 157 | + |
| 158 | + _resolve_tied_lm_head(model, embed_cw, packers) |
| 159 | + del embed_cw |
| 160 | + |
| 161 | + _validate_no_meta(model) |
| 162 | + model.eval() |
| 163 | + |
| 164 | + print(f"Model: {config.num_hidden_layers} layers, hidden={config.hidden_size}") |
| 165 | + return model, config |
0 commit comments