diff --git a/csrc/activation/silu_and_mul.cu b/csrc/activation/silu_and_mul.cu index 08c05c7a..efe3a04e 100644 --- a/csrc/activation/silu_and_mul.cu +++ b/csrc/activation/silu_and_mul.cu @@ -171,8 +171,36 @@ __global__ void silu_and_mul_kernel(const T* gate, const T* up, T* out, int64_t } } +template +__global__ void silu_and_mul_rows(const T* gate, const T* up, T* out, + int64_t width, int64_t rows, int64_t gate_stride, + int64_t up_stride, int64_t work_per_row) { + const int64_t first = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + const int64_t stride = static_cast(gridDim.x) * blockDim.x; + for (int64_t i = first; i < rows * work_per_row; i += stride) { + const int64_t row = i / work_per_row; + const int64_t col = i % work_per_row; + if constexpr (aligned) { + constexpr int elements = 16 / sizeof(T); + constexpr int pairs = 16 / sizeof(typename Math::Pair); + const int64_t offset = col * elements; + Vector g = load_vector(gate + row * gate_stride, offset, width); + Vector u = load_vector(up + row * up_stride, offset, width); + Vector result; +#pragma unroll + for (int j = 0; j < pairs; ++j) { + result.pairs[j] = Math::compute(g.pairs[j], u.pairs[j]); + } + *reinterpret_cast(out + row * width + offset) = + *reinterpret_cast(&result); + } else { + out[i] = compute_scalar(gate[row * gate_stride + col], up[row * up_stride + col]); + } + } +} + template -void launch(const at::Tensor& gate, const at::Tensor& up, at::Tensor& out) { +void launch(const at::Tensor& gate, const at::Tensor& up, at::Tensor& out, bool contiguous) { const T* g = reinterpret_cast(gate.const_data_ptr()); const T* u = reinterpret_cast(up.const_data_ptr()); T* result = reinterpret_cast(out.mutable_data_ptr()); @@ -182,6 +210,27 @@ void launch(const at::Tensor& gate, const at::Tensor& up, at::Tensor& out) { reinterpret_cast(result)) & 15) == 0; const int64_t count = gate.numel(); constexpr int threads = 256; + auto stream = c10::cuda::getCurrentCUDAStream(gate.get_device()); + if (!contiguous) { + const int64_t width = gate.size(1); + const int64_t rows = gate.size(0); + const int64_t gs = gate.stride(0); + const int64_t us = up.stride(0); + constexpr int elements = 16 / sizeof(T); + const bool aligned = vectorized && (width | gs | us) % elements == 0; + const int64_t work_per_row = aligned ? width / elements : width; + const int blocks = static_cast(std::min( + (rows * work_per_row + threads - 1) / threads, 4096)); + if (aligned) { + silu_and_mul_rows<<>>( + g, u, result, width, rows, gs, us, work_per_row); + } else { + silu_and_mul_rows<<>>( + g, u, result, width, rows, gs, us, work_per_row); + } + C10_CUDA_KERNEL_LAUNCH_CHECK(); + return; + } bool scalar = false; if (!vectorized) { // Use 160 reference vector blocks per SM to determine the element cutoff. @@ -204,7 +253,6 @@ void launch(const at::Tensor& gate, const at::Tensor& up, at::Tensor& out) { } } const int blocks = static_cast(std::min((work + threads - 1) / threads, max_blocks)); - auto stream = c10::cuda::getCurrentCUDAStream(gate.get_device()); if (vectorized) { silu_and_mul_kernel<<>>(g, u, result, count); } else if (scalar) { @@ -227,8 +275,10 @@ at::Tensor silu_and_mul_cuda(const at::Tensor& gate, const at::Tensor& up) { gate.scalar_type() == at::kBFloat16, "silu_and_mul supports float32, float16 and bfloat16"); - TORCH_CHECK(gate.is_contiguous() && up.is_contiguous(), - "silu_and_mul expects contiguous inputs"); + const bool contiguous = gate.is_contiguous() && up.is_contiguous(); + TORCH_CHECK(contiguous || + (gate.dim() == 2 && gate.stride(1) == 1 && up.stride(1) == 1), + "silu_and_mul expects contiguous inputs or 2D inputs with contiguous rows"); TORCH_CHECK(!at::GradMode::is_enabled() || (!gate.requires_grad() && !up.requires_grad()), "silu_and_mul is inference-only; use torch.no_grad() or silu_and_mul_reference"); @@ -238,9 +288,9 @@ at::Tensor silu_and_mul_cuda(const at::Tensor& gate, const at::Tensor& up) { return out; } switch (gate.scalar_type()) { - case at::kHalf: launch<__half>(gate, up, out); break; - case at::kBFloat16: launch<__nv_bfloat16>(gate, up, out); break; - case at::kFloat: launch(gate, up, out); break; + case at::kHalf: launch<__half>(gate, up, out, contiguous); break; + case at::kBFloat16: launch<__nv_bfloat16>(gate, up, out, contiguous); break; + case at::kFloat: launch(gate, up, out, contiguous); break; default: TORCH_CHECK(false, "unsupported dtype"); } return out; diff --git a/docs/kernels.md b/docs/kernels.md index 9f01fc48..694d3f9a 100644 --- a/docs/kernels.md +++ b/docs/kernels.md @@ -29,10 +29,11 @@ are FP32, FP16 and BF16. The output owns new storage and preserves input shape, dtype and device. Neither input is modified. The Torch reference preserves the intermediate SiLU rounding of the existing MLP expression. -Separate inputs avoid concatenating Ouro and Nanbeige's separate projection -outputs. The reference also accepts Huginn's noncontiguous split-projection -views. The native entry requires both inputs to be contiguous; it neither pads -nor copies incompatible inputs. +The native entry accepts contiguous inputs and 2D inputs with unit column +strides. Ouro's fused gate/up projection produces two such views into one +matrix. The kernel reads both row strides directly with 16-byte vector loads +when the rows and their starts are aligned, or scalar loads otherwise. +Inputs outside these layouts are rejected without copying. `silu_and_mul(gate, up)` uses PyTorch dispatch: CUDA inputs use the native kernel when the extension is installed; CPU inputs and installations without the diff --git a/tests/test_activation.py b/tests/test_activation.py index 0b877a0b..e3be3148 100644 --- a/tests/test_activation.py +++ b/tests/test_activation.py @@ -307,9 +307,26 @@ def test_silu_and_mul_cuda_special_values_and_underflow(dtype, offsets): @pytest.mark.gpu -def test_silu_and_mul_cuda_rejects_noncontiguous_input_without_copying(): - gate, up = torch.randn(2, 14, device="cuda").chunk(2, dim=-1) - with pytest.raises(RuntimeError, match="contiguous inputs"): +@pytest.mark.parametrize("rows,width", [(8, 5632), (32, 5632), (128, 5632), (3, 13)]) +def test_silu_and_mul_cuda_consumes_packed_projection_without_repacking(rows, width): + packed = torch.randn((rows, 2 * width), device="cuda", dtype=torch.bfloat16) + gate, up = packed.split(width, dim=-1) + assert not gate.is_contiguous() and not up.is_contiguous() + actual = silu_and_mul(gate, up) + torch.testing.assert_close(actual, silu_and_mul_reference(gate, up), rtol=0, atol=0) + + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + actual = silu_and_mul(gate, up) + packed.normal_() + graph.replay() + torch.testing.assert_close(actual, silu_and_mul_reference(gate, up), rtol=0, atol=0) + + +@pytest.mark.gpu +def test_silu_and_mul_cuda_rejects_nonunit_column_stride_without_copying(): + gate, up = torch.randn(2, 28, device="cuda")[:, ::2].chunk(2, dim=-1) + with pytest.raises(RuntimeError, match="contiguous rows"): silu_and_mul(gate, up) diff --git a/tests/test_fused_projections.py b/tests/test_fused_projections.py new file mode 100644 index 00000000..d37dfb3a --- /dev/null +++ b/tests/test_fused_projections.py @@ -0,0 +1,118 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Exercise Ouro's packed weights through checkpoint and GPU execution paths.""" + +import pickle + +import pytest +import torch +from torch.nn import functional as F + +from tests.helpers import tiny_ouro_config +from vllm_rlt.models.ouro import OuroForCausalLM, OuroMLP + + +def test_reload_legacy_weights_updates_a_previously_used_mlp(): + model = OuroForCausalLM(tiny_ouro_config()) + mlp = model.model.layers[0].mlp + hidden = torch.ones(4, model.config.hidden_size) + before = mlp(hidden) + assert torch.count_nonzero(before) + + original = mlp.state_dict()["up_proj.weight"].clone() + missing, unexpected = mlp.load_state_dict( + {"gate_proj.weight": torch.zeros_like(original)}, strict=False + ) + assert set(missing) == {"up_proj.weight", "down_proj.weight"} + assert not unexpected + assert torch.equal(mlp.state_dict()["up_proj.weight"], original) + torch.testing.assert_close(mlp(hidden), torch.zeros_like(before), atol=0, rtol=0) + + +@pytest.mark.parametrize("roundtrip", ["convert", "pickle", "load", "assign"]) +def test_checkpoint_views_share_one_weight_after_roundtrip(roundtrip): + config = tiny_ouro_config(num_key_value_heads=1) + original = OuroForCausalLM(config) + checkpoint = original.state_dict() + if roundtrip == "convert": + model = original.bfloat16() + elif roundtrip == "pickle": + model = pickle.loads(pickle.dumps(original)) + elif roundtrip == "load": + model = OuroForCausalLM(config) + model.load_state_dict(checkpoint) + else: + with torch.device("meta"): + model = OuroForCausalLM(config) + model.load_state_dict(checkpoint, assign=True) + + weights = model.state_dict() + assert weights.keys() == checkpoint.keys() + for name, value in weights.items(): + assert torch.equal(value, checkpoint[name].to(dtype=value.dtype)) + for layer in model.model.layers: + for module, names in ( + (layer.self_attn, ("q_proj", "k_proj", "v_proj")), + (layer.mlp, ("gate_proj", "up_proj")), + ): + expected_offset = 0 + for name in names: + part = module.state_dict()[f"{name}.weight"] + assert part.untyped_storage().data_ptr() == module.input_weight.data_ptr() + assert part.storage_offset() == expected_offset + expected_offset += part.numel() + assert expected_offset == module.input_weight.numel() + assert module.input_weight.untyped_storage().nbytes() == ( + expected_offset * module.input_weight.element_size() + ) + + +@pytest.mark.parametrize("corruption", ["missing", "shape", "internal"]) +def test_strict_load_validates_legacy_fused_keys(corruption): + model = OuroForCausalLM(tiny_ouro_config()) + checkpoint = model.state_dict() + key = "model.layers.0.self_attn.k_proj.weight" + if corruption == "missing": + del checkpoint[key] + elif corruption == "shape": + checkpoint[key] = checkpoint[key][:-1] + else: + key = "model.layers.0.self_attn.input_weight" + checkpoint[key] = model.model.layers[0].self_attn.input_weight + with pytest.raises(RuntimeError, match=key): + model.load_state_dict(checkpoint) + + +@pytest.mark.gpu +def test_mlp_output_is_bitwise_identical_to_the_unfused_expression(): + from vllm_rlt.kernels._extension import load_extension + + load_extension() + torch.manual_seed(1) + config = tiny_ouro_config(hidden_size=64, intermediate_size=128) + mlp = OuroMLP(config).to("cuda", torch.bfloat16).eval() + hidden = torch.randn(4, config.hidden_size, device="cuda", dtype=torch.bfloat16) + params = mlp.state_dict() + with torch.no_grad(): + expected = mlp.down_proj( + F.silu(F.linear(hidden, params["gate_proj.weight"])) + * F.linear(hidden, params["up_proj.weight"]) + ) + got = mlp(hidden) + torch.testing.assert_close(got, expected, atol=0, rtol=0) + + +@pytest.mark.gpu +def test_attention_split_matches_separate_projections_within_bf16_rounding(): + torch.manual_seed(2) + config = tiny_ouro_config(hidden_size=64, num_key_value_heads=1) + model = OuroForCausalLM(config).to("cuda", torch.bfloat16) + attn = model.model.layers[0].self_attn + hidden = torch.randn(4, config.hidden_size, device="cuda", dtype=torch.bfloat16) + params = attn.state_dict() + with torch.no_grad(): + parts = attn.project(hidden) + separate = tuple(F.linear(hidden, params[f"{name}_proj.weight"]) for name in "qkv") + for got, exp in zip(parts, separate): + diff = (got.float() - exp.float()).abs().max().item() + scale = max(exp.float().abs().max().item(), 1e-9) + assert diff / scale < 0.0078, f"relative diff {diff / scale:.5f} exceeds 1 BF16 ULP" diff --git a/tests/test_ouro.py b/tests/test_ouro.py index e7f29cd3..a5af9db9 100644 --- a/tests/test_ouro.py +++ b/tests/test_ouro.py @@ -8,6 +8,7 @@ import pytest import torch from safetensors.torch import save_file +from torch.nn import functional as F from tests.helpers import make_cpu_cache, tiny_ouro_config from tests.reference import dense_reference @@ -21,6 +22,13 @@ def model(): return OuroForCausalLM(tiny_ouro_config()) +def _unfused_mlp(layer, hidden): + weights = layer.state_dict() + gate = F.linear(hidden, weights["gate_proj.weight"]) + up = F.linear(hidden, weights["up_proj.weight"]) + return F.linear(F.silu(gate) * up, weights["down_proj.weight"]) + + @pytest.mark.gpu @pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16, torch.float32]) @pytest.mark.parametrize("rows", [1, 7, 32]) @@ -28,10 +36,8 @@ def test_cuda_mlp_matches_torch_expression(dtype, rows): torch.manual_seed(72) layer = OuroMLP(tiny_ouro_config(intermediate_size=17)).to(device="cuda", dtype=dtype) layer.requires_grad_(False) - hidden = torch.randn(rows, layer.gate_proj.in_features, device="cuda", dtype=dtype) - expected = layer.down_proj( - torch.nn.functional.silu(layer.gate_proj(hidden)) * layer.up_proj(hidden) - ) + hidden = torch.randn(rows, layer.input_weight.shape[1], device="cuda", dtype=dtype) + expected = _unfused_mlp(layer, hidden) torch.testing.assert_close(layer(hidden), expected, rtol=0, atol=0) @@ -55,10 +61,10 @@ def import_module(name, *args, **kwargs): assert torch._C._dispatch_has_kernel_for_dispatch_key( 'vllm_rlt::silu_and_mul', 'CUDA') == {native_available} layer = OuroMLP(tiny_ouro_config()).cuda().bfloat16().requires_grad_(False) - hidden = torch.randn(3, layer.gate_proj.in_features, + hidden = torch.randn(3, layer.input_weight.shape[1], device='cuda', dtype=torch.bfloat16) - expected = layer.down_proj( - torch.nn.functional.silu(layer.gate_proj(hidden)) * layer.up_proj(hidden)) + from tests.test_ouro import _unfused_mlp + expected = _unfused_mlp(layer, hidden) with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU]) as prof: actual = layer(hidden) torch.testing.assert_close(actual, expected, rtol=0, atol=0) @@ -74,7 +80,7 @@ def test_cuda_mlp_graph_replays_updated_hidden(): layer = OuroMLP(tiny_ouro_config(intermediate_size=17)).cuda().bfloat16().requires_grad_(False) stream = torch.cuda.Stream() with torch.cuda.stream(stream): - hidden = torch.randn(3, layer.gate_proj.in_features, device="cuda", dtype=torch.bfloat16) + hidden = torch.randn(3, layer.input_weight.shape[1], device="cuda", dtype=torch.bfloat16) for _ in range(3): layer(hidden) stream.synchronize() @@ -83,9 +89,7 @@ def test_cuda_mlp_graph_replays_updated_hidden(): actual = layer(hidden) hidden.fill_(0.5) graph.replay() - expected = layer.down_proj( - torch.nn.functional.silu(layer.gate_proj(hidden)) * layer.up_proj(hidden) - ) + expected = _unfused_mlp(layer, hidden) torch.testing.assert_close(actual, expected, rtol=0, atol=0) @@ -226,7 +230,7 @@ def snapshot_download(**kwargs): ) monkeypatch.setattr("huggingface_hub.snapshot_download", snapshot_download) loaded = OuroForCausalLM.from_pretrained("test-org/checkpoint", revision="test-revision") - for name, parameter in loaded.named_parameters(): + for name, parameter in loaded.state_dict().items(): torch.testing.assert_close(parameter, model.state_dict()[name].bfloat16(), atol=0, rtol=0) assert loaded.model.rotary_emb.inv_freq.dtype == torch.float32 assert called["revision"] == "test-revision" diff --git a/vllm_rlt/kernels/activation.py b/vllm_rlt/kernels/activation.py index 4123006c..86d95e5c 100644 --- a/vllm_rlt/kernels/activation.py +++ b/vllm_rlt/kernels/activation.py @@ -22,7 +22,8 @@ def silu_and_mul_reference(gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor Inputs have equal shape, dtype and device. The result has the same shape, dtype and device and owns new storage. Noncontiguous inputs are supported - by this reference; the native entry requires contiguous inputs. + by this reference; the native entry supports contiguous tensors and 2D + tensors with contiguous rows. """ _validate_inputs(gate, up) return F.silu(gate) * up diff --git a/vllm_rlt/layers/fused_projections.py b/vllm_rlt/layers/fused_projections.py new file mode 100644 index 00000000..56089faf --- /dev/null +++ b/vllm_rlt/layers/fused_projections.py @@ -0,0 +1,87 @@ +# SPDX-License-Identifier: Apache-2.0 +"""One linear weight with disjoint row slices for legacy checkpoint keys.""" + +import torch +from torch import nn +from torch.nn import functional as F + + +class FusedProjectionLayer(nn.Module): + """Base for Ouro layers whose input projections share a single parameter.""" + + def __init__(self, in_features: int, projections: tuple[tuple[str, int], ...]) -> None: + super().__init__() + self.projection_sizes = tuple(width for _, width in projections) + self.checkpoint_slices = {} + offset = 0 + for name, width in projections: + self.checkpoint_slices[f"{name}.weight"] = slice(offset, offset + width) + offset += width + self.input_weight = nn.Parameter(torch.empty(offset, in_features)) + for rows in self.checkpoint_slices.values(): + nn.init.kaiming_uniform_(self.input_weight[rows], a=5**0.5) + + def project(self, hidden: torch.Tensor) -> tuple[torch.Tensor, ...]: + return F.linear(hidden, self.input_weight).split(self.projection_sizes, dim=-1) + + def _save_to_state_dict(self, destination, prefix, keep_vars): + super()._save_to_state_dict(destination, prefix, keep_vars) + weight = destination.pop(prefix + "input_weight") + for name, rows in self.checkpoint_slices.items(): + destination[prefix + name] = weight[rows] + + @torch.no_grad() + def _load_from_state_dict( + self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ): + packed_key = prefix + "input_weight" + if packed_key in state_dict: + unexpected_keys.append(packed_key) + pieces = {} + for name, rows in self.checkpoint_slices.items(): + key = prefix + name + if key not in state_dict: + missing_keys.append(key) + continue + piece = state_dict.pop(key) + expected = self.input_weight[rows].shape + if not isinstance(piece, torch.Tensor) or piece.shape != expected: + error_msgs.append(f"size or tensor type mismatch for {key}: expected {expected}") + continue + pieces[name] = piece + + assign = local_metadata.get("assign_to_params_buffers", False) + weight = self.input_weight.detach() + if pieces and assign: + first = next(iter(pieces.values())) + compatible = all( + part.device == first.device and part.dtype == first.dtype + for part in pieces.values() + ) + partial_meta = ( + weight.is_meta and not first.is_meta and len(pieces) != len(self.checkpoint_slices) + ) + if not compatible or partial_meta: + error_msgs.append(f"incompatible slices for assigning fused weight at {prefix}") + pieces.clear() + else: + weight = torch.empty_like(weight, device=first.device, dtype=first.dtype) + for name, rows in self.checkpoint_slices.items(): + if name not in pieces: + weight[rows].copy_(self.input_weight.detach()[rows]) + + for name, piece in pieces.items(): + rows = self.checkpoint_slices[name] + if not assign and weight.is_meta and not piece.is_meta: + # Let PyTorch report its normal no-op warning for meta parameters. + if len(pieces) == len(self.checkpoint_slices): + weight = torch.cat(tuple(pieces.values()), dim=0) + break + try: + weight[rows].copy_(piece) + except Exception as exc: + error_msgs.append(f"copying {prefix + name} into the fused weight: {exc}") + state_dict[packed_key] = weight + super()._load_from_state_dict( + state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ) diff --git a/vllm_rlt/models/ouro.py b/vllm_rlt/models/ouro.py index 5041fdf3..83fb97a7 100644 --- a/vllm_rlt/models/ouro.py +++ b/vllm_rlt/models/ouro.py @@ -27,6 +27,7 @@ apply_rotary_pos_emb, rotate_half, ) +from vllm_rlt.layers.fused_projections import FusedProjectionLayer if TYPE_CHECKING: from vllm_rlt.core.kv_cache_manager import KVCacheManager @@ -151,23 +152,17 @@ def to_dict(self) -> dict[str, Any]: _rotate_half = rotate_half -class OuroAttention(nn.Module): +class OuroAttention(FusedProjectionLayer): def __init__(self, config: OuroConfig, layer_idx: int) -> None: - super().__init__() + query_width = config.num_attention_heads * config.head_dim + kv_width = config.num_key_value_heads * config.head_dim + super().__init__( + config.hidden_size, + (("q_proj", query_width), ("k_proj", kv_width), ("v_proj", kv_width)), + ) self.config = config self.layer_idx = layer_idx - self.q_proj = nn.Linear( - config.hidden_size, config.num_attention_heads * config.head_dim, bias=False - ) - self.k_proj = nn.Linear( - config.hidden_size, config.num_key_value_heads * config.head_dim, bias=False - ) - self.v_proj = nn.Linear( - config.hidden_size, config.num_key_value_heads * config.head_dim, bias=False - ) - self.o_proj = nn.Linear( - config.num_attention_heads * config.head_dim, config.hidden_size, bias=False - ) + self.o_proj = nn.Linear(query_width, config.hidden_size, bias=False) def forward( self, @@ -177,9 +172,7 @@ def forward( cache: "KVCacheManager", ) -> torch.Tensor: shape = (hidden.shape[0], -1, self.config.head_dim) - q = self.q_proj(hidden).view(shape) - k = self.k_proj(hidden).view(shape) - v = self.v_proj(hidden).view(shape) + q, k, v = (part.view(shape) for part in self.project(hidden)) cos, sin = position_embeddings q, k = apply_rotary_pos_emb(q, k, cos, sin) cache._write_prepared(self.layer_idx, batch, k, v) @@ -187,15 +180,15 @@ def forward( return self.o_proj(output.reshape(hidden.shape[0], -1)) -class OuroMLP(nn.Module): +class OuroMLP(FusedProjectionLayer): def __init__(self, config: OuroConfig) -> None: - super().__init__() - self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) - self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) + width = config.intermediate_size + super().__init__(config.hidden_size, (("gate_proj", width), ("up_proj", width))) self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False) def forward(self, hidden: torch.Tensor) -> torch.Tensor: - return self.down_proj(silu_and_mul(self.gate_proj(hidden), self.up_proj(hidden))) + gate, up = self.project(hidden) + return self.down_proj(silu_and_mul(gate, up)) class OuroDecoderLayer(nn.Module): @@ -235,19 +228,27 @@ def __init__(self, config: OuroConfig) -> None: class OuroForCausalLM(nn.Module): - """Inference-only native Ouro-1.4B with checkpoint-compatible parameter names.""" + """Inference-only native Ouro-1.4B with checkpoint-compatible state dict keys.""" def __init__(self, config: OuroConfig) -> None: super().__init__() self.config = config self.model = OuroModel(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) - self.apply(self._initialize) + # A fused layer owns the input projections, which precede its output + # projection in the checkpoint and the original RNG draw order. + for module in self.modules(): + self._initialize(module) self.requires_grad_(False) self.eval() def _initialize(self, module: nn.Module) -> None: - if isinstance(module, (nn.Linear, nn.Embedding)): + if isinstance(module, FusedProjectionLayer): + for rows in module.checkpoint_slices.values(): + nn.init.normal_( + module.input_weight[rows], mean=0, std=self.config.initializer_range + ) + elif isinstance(module, (nn.Linear, nn.Embedding)): nn.init.normal_(module.weight, mean=0, std=self.config.initializer_range) if isinstance(module, nn.Linear) and module.bias is not None: nn.init.zeros_(module.bias) @@ -340,7 +341,7 @@ def from_pretrained( ) with torch.device("meta"): model = cls(config) - expected = {name: tuple(parameter.shape) for name, parameter in model.named_parameters()} + expected = {name: tuple(tensor.shape) for name, tensor in model.state_dict().items()} discovered: dict[str, Path] = {} # Validate every key and shape before allocating model weight memory. for shard in shards: @@ -360,12 +361,24 @@ def from_pretrained( raise ValueError(f"Missing checkpoint tensors: {sorted(missing)}") if index is not None and set(index) != set(expected): raise ValueError("Checkpoint index does not match Ouro parameter names") + fused_slices = {} + for prefix, module in model.named_modules(): + if isinstance(module, FusedProjectionLayer): + module.input_weight = nn.Parameter( + torch.empty_like(module.input_weight, device=device, dtype=dtype), + requires_grad=False, + ) + for name, rows in module.checkpoint_slices.items(): + fused_slices[f"{prefix}.{name}"] = module.input_weight[rows] for shard in shards: with safe_open(shard, framework="pt", device="cpu") as checkpoint: for name in checkpoint.keys(): tensor = checkpoint.get_tensor(name) if not tensor.is_floating_point(): raise ValueError(f"Checkpoint tensor must be floating point: {name}") + if name in fused_slices: + fused_slices[name].copy_(tensor) + continue module_path, parameter_name = name.rsplit(".", 1) module = model.get_submodule(module_path) setattr(