|
| 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 | +"""Fused cross-entropy training op (`et_vk.fused_ce`) export + fp64 golden. |
| 8 | +
|
| 9 | +`fused_ce(logits[M,V], labels[M], n_valid) -> (loss, dlogits[M,V])` computes the |
| 10 | +mean-over-valid CE loss and its gradient in one op (labels < 0 are ignored/pad). |
| 11 | +Golden is the fp64 reference (`logsumexp - picked`, `softmax - onehot`), the same math |
| 12 | +torch's cross_entropy uses; the native test reconstructs the deterministic inputs. |
| 13 | +""" |
| 14 | + |
| 15 | +import os |
| 16 | +import unittest |
| 17 | +from dataclasses import dataclass |
| 18 | + |
| 19 | +import numpy as np |
| 20 | +import torch |
| 21 | + |
| 22 | +from executorch.backends.vulkan import VulkanPartitioner |
| 23 | +from executorch.exir import to_edge_transform_and_lower |
| 24 | + |
| 25 | + |
| 26 | +@dataclass(frozen=True) |
| 27 | +class CeConfig: |
| 28 | + name: str |
| 29 | + m: int # rows (valid + pad positions) |
| 30 | + v: int # vocab |
| 31 | + n_pad: int = 0 # trailing rows with label = -1 (ignored) |
| 32 | + |
| 33 | + |
| 34 | +# Mirrored by the C++ kFusedCeConfigs table. Llama-3.2-1B vocab = 128256. |
| 35 | +CONFIGS = [ |
| 36 | + CeConfig("tiny", 4, 32), |
| 37 | + CeConfig("masked", 8, 128, n_pad=3), # some ignored labels |
| 38 | + CeConfig("llama_vocab", 16, 128256), # real vocab width |
| 39 | +] |
| 40 | + |
| 41 | + |
| 42 | +def _inputs(cfg: CeConfig): |
| 43 | + """Deterministic logits [M,V] + labels [M] (last n_pad = -1); reconstructable in C++.""" |
| 44 | + flat = np.arange(cfg.m * cfg.v, dtype=np.int64) |
| 45 | + logits = torch.from_numpy( |
| 46 | + (((flat % 23) - 11).astype(np.float32) / np.float32(8.0)).reshape(cfg.m, cfg.v) |
| 47 | + ) |
| 48 | + labels = torch.from_numpy((np.arange(cfg.m, dtype=np.int64) * 7 + 3) % cfg.v) |
| 49 | + if cfg.n_pad: |
| 50 | + labels[cfg.m - cfg.n_pad :] = -1 |
| 51 | + n_valid = float(max(1, cfg.m - cfg.n_pad)) |
| 52 | + return logits, labels, n_valid |
| 53 | + |
| 54 | + |
| 55 | +def _fp64_golden(logits: torch.Tensor, labels: torch.Tensor, n_valid: float): |
| 56 | + mask = labels >= 0 |
| 57 | + safe = labels.clamp(min=0).long() |
| 58 | + lg = logits.double() |
| 59 | + lse = torch.logsumexp(lg, dim=-1) |
| 60 | + picked = lg.gather(-1, safe[:, None]).squeeze(-1) |
| 61 | + loss = torch.where(mask, (lse - picked) / n_valid, torch.zeros_like(lse)).sum() |
| 62 | + softmax = torch.softmax(lg, dim=-1) |
| 63 | + onehot = torch.nn.functional.one_hot(safe, logits.shape[-1]).double() |
| 64 | + dlogits = torch.where( |
| 65 | + mask[:, None], (softmax - onehot) / n_valid, torch.zeros_like(softmax) |
| 66 | + ) |
| 67 | + return loss.to(torch.float32), dlogits.to(torch.float32) |
| 68 | + |
| 69 | + |
| 70 | +class _CeModule(torch.nn.Module): |
| 71 | + def forward(self, logits, labels, n_valid): |
| 72 | + return torch.ops.et_vk.fused_ce(logits, labels, n_valid) |
| 73 | + |
| 74 | + |
| 75 | +def _export(logits, labels, n_valid): |
| 76 | + ep = torch.export.export(_CeModule(), (logits, labels, n_valid)) |
| 77 | + return to_edge_transform_and_lower( |
| 78 | + ep, partitioner=[VulkanPartitioner()] |
| 79 | + ).to_executorch() |
| 80 | + |
| 81 | + |
| 82 | +class TestFusedCe(unittest.TestCase): |
| 83 | + def test_export_delegates(self) -> None: |
| 84 | + for cfg in CONFIGS: |
| 85 | + if cfg.v > 1024: # width-independent; skip the 128k fixture |
| 86 | + continue |
| 87 | + with self.subTest(config=cfg.name): |
| 88 | + logits, labels, n_valid = _inputs(cfg) |
| 89 | + et = _export(logits, labels, n_valid) |
| 90 | + found = any( |
| 91 | + d.id == "VulkanBackend" |
| 92 | + for plan in et.executorch_program.execution_plan |
| 93 | + for d in plan.delegates |
| 94 | + ) |
| 95 | + self.assertTrue(found, f"no VulkanBackend delegate in {cfg.name}") |
| 96 | + |
| 97 | + def test_op_matches_fp64_golden(self) -> None: |
| 98 | + for cfg in CONFIGS: |
| 99 | + if cfg.v > 1024: |
| 100 | + continue |
| 101 | + with self.subTest(config=cfg.name): |
| 102 | + logits, labels, n_valid = _inputs(cfg) |
| 103 | + loss, dlogits = torch.ops.et_vk.fused_ce(logits, labels, n_valid) |
| 104 | + g_loss, g_dlogits = _fp64_golden(logits, labels, n_valid) |
| 105 | + torch.testing.assert_close(loss, g_loss, atol=5e-4, rtol=1e-3) |
| 106 | + torch.testing.assert_close(dlogits, g_dlogits, atol=5e-4, rtol=1e-3) |
| 107 | + |
| 108 | + |
| 109 | +def export_fused_ce_model(cfg: CeConfig, pte_path: str, golden_path: str) -> None: |
| 110 | + logits, labels, n_valid = _inputs(cfg) |
| 111 | + et = _export(logits, labels, n_valid) |
| 112 | + with open(pte_path, "wb") as f: |
| 113 | + f.write(et.buffer) |
| 114 | + g_loss, g_dlogits = _fp64_golden(logits, labels, n_valid) |
| 115 | + # loss scalar then dlogits, both raw LE fp32 |
| 116 | + np.concatenate([g_loss.reshape(1).numpy(), g_dlogits.reshape(-1).numpy()]).astype( |
| 117 | + "<f4" |
| 118 | + ).tofile(golden_path) |
| 119 | + print(f"Exported {pte_path}; golden {golden_path}") |
| 120 | + |
| 121 | + |
| 122 | +def export_all_fused_ce_models(out_dir: str) -> None: |
| 123 | + for cfg in CONFIGS: |
| 124 | + pte = os.path.join(out_dir, f"fused_ce_{cfg.name}.pte") |
| 125 | + golden = os.path.join(out_dir, f"fused_ce_{cfg.name}.golden.bin") |
| 126 | + export_fused_ce_model(cfg, pte, golden) |
| 127 | + |
| 128 | + |
| 129 | +if __name__ == "__main__": |
| 130 | + unittest.main() |
0 commit comments