|
| 1 | +"""llm_conf.sdpa_backends / llm_conf.torch_compile on both copies of FunASRNano (the package |
| 2 | +class and the recipe's model.py, imported by path). CPU-only, no weights: tiny stand-ins.""" |
| 3 | + |
| 4 | +import importlib.util |
| 5 | +import os |
| 6 | +import re |
| 7 | +import sys |
| 8 | +import types |
| 9 | + |
| 10 | +import pytest |
| 11 | +import torch |
| 12 | +import torch.nn as nn |
| 13 | + |
| 14 | +from funasr.models.fun_asr_nano import model as funasr_model |
| 15 | +from funasr.register import tables |
| 16 | + |
| 17 | +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 18 | +RECIPE_DIR = os.path.join(REPO, "examples", "industrial_data_pretraining", "fun_asr_nano") |
| 19 | + |
| 20 | + |
| 21 | +class _TinyDecoder(nn.Module): |
| 22 | + """Stands in for the HF decoder stack (``llm.model``); records every eager call.""" |
| 23 | + |
| 24 | + def __init__(self, dim): |
| 25 | + super().__init__() |
| 26 | + self.proj = nn.Linear(dim, dim) |
| 27 | + self.eager_calls = [] |
| 28 | + |
| 29 | + def forward(self, input_ids=None, inputs_embeds=None, **kwargs): |
| 30 | + if not torch.compiler.is_compiling(): |
| 31 | + cudnn = torch.backends.cuda.cudnn_sdp_enabled() |
| 32 | + self.eager_calls.append({"batch": int(inputs_embeds.shape[0]), "cudnn": cudnn}) |
| 33 | + return self.proj(inputs_embeds) |
| 34 | + |
| 35 | + |
| 36 | +class _TinyLLM(nn.Module): |
| 37 | + def __init__(self, dim=8, vocab=16): |
| 38 | + super().__init__() |
| 39 | + self.model, self.embed = _TinyDecoder(dim), nn.Embedding(vocab, dim) |
| 40 | + |
| 41 | + def get_input_embeddings(self): |
| 42 | + return self.embed |
| 43 | + |
| 44 | + |
| 45 | +class _TinyEncoder(nn.Module): |
| 46 | + def __init__(self, input_size=80, **kwargs): |
| 47 | + super().__init__() |
| 48 | + self.lin = nn.Linear(input_size, 4) |
| 49 | + |
| 50 | + def output_size(self): |
| 51 | + return 4 |
| 52 | + |
| 53 | + |
| 54 | +class _TinyAdaptor(nn.Module): |
| 55 | + def __init__(self, encoder_dim=4, llm_dim=8, **kwargs): |
| 56 | + super().__init__() |
| 57 | + self.lin = nn.Linear(encoder_dim, llm_dim) |
| 58 | + |
| 59 | + |
| 60 | +def _load_recipe_model(): |
| 61 | + previous = tables.model_classes.get("FunASRNano") |
| 62 | + if RECIPE_DIR not in sys.path: |
| 63 | + sys.path.insert(0, RECIPE_DIR) # the recipe imports ``ctc`` and ``tools.utils`` bare |
| 64 | + path = os.path.join(RECIPE_DIR, "model.py") |
| 65 | + spec = importlib.util.spec_from_file_location("fun_asr_nano_recipe_model", path) |
| 66 | + module = importlib.util.module_from_spec(spec) |
| 67 | + sys.modules[spec.name] = module # tables.register() calls inspect.getfile on the class |
| 68 | + try: |
| 69 | + spec.loader.exec_module(module) |
| 70 | + except ImportError as exc: |
| 71 | + sys.modules.pop(spec.name, None) |
| 72 | + pytest.skip(f"recipe model.py not importable here: {exc}") |
| 73 | + finally: |
| 74 | + tables.model_classes["FunASRNano"] = previous # the package class, registered at import |
| 75 | + return module.FunASRNano |
| 76 | + |
| 77 | + |
| 78 | +@pytest.fixture(scope="module", params=["funasr", "recipe"]) |
| 79 | +def model_class(request): |
| 80 | + return funasr_model.FunASRNano if request.param == "funasr" else _load_recipe_model() |
| 81 | + |
| 82 | + |
| 83 | +@pytest.fixture |
| 84 | +def build(monkeypatch, model_class): |
| 85 | + """``build(llm_conf) -> FunASRNano`` on the CPU, with the transformers loaders stubbed.""" |
| 86 | + fake = types.ModuleType("transformers") |
| 87 | + fake.AutoConfig = types.SimpleNamespace(from_pretrained=lambda path, **kw: {}) |
| 88 | + fake.AutoModelForCausalLM = types.SimpleNamespace(from_config=lambda config, **kw: _TinyLLM()) |
| 89 | + monkeypatch.setattr(funasr_model, "AutoConfig", fake.AutoConfig) # bound at import time |
| 90 | + monkeypatch.setattr(funasr_model, "AutoModelForCausalLM", fake.AutoModelForCausalLM) |
| 91 | + monkeypatch.setitem(sys.modules, "transformers", fake) # the recipe imports in __init__ |
| 92 | + monkeypatch.setitem(tables.encoder_classes, "TinyEnc", _TinyEncoder) |
| 93 | + monkeypatch.setitem(tables.adaptor_classes, "TinyAdp", _TinyAdaptor) |
| 94 | + kw = dict(audio_encoder="TinyEnc", audio_adaptor="TinyAdp", llm="tiny") |
| 95 | + return lambda c: model_class(audio_encoder_conf={}, audio_adaptor_conf={}, llm_conf=c, **kw) |
| 96 | + |
| 97 | + |
| 98 | +def _run(model, batch): |
| 99 | + device = next(model.llm.parameters()).device |
| 100 | + return model.llm.model.forward(inputs_embeds=torch.zeros(batch, 3, 8, device=device)) |
| 101 | + |
| 102 | + |
| 103 | +def test_default_leaves_sdpa_flag_and_forward_alone(build): |
| 104 | + flag = torch.backends.cuda.cudnn_sdp_enabled() |
| 105 | + model = build({}) |
| 106 | + assert torch.backends.cuda.cudnn_sdp_enabled() == flag |
| 107 | + assert "forward" not in model.llm.model.__dict__ # still the class method |
| 108 | + _run(model, 2) |
| 109 | + assert model.llm.model.eager_calls[-1]["cudnn"] == flag |
| 110 | + |
| 111 | + |
| 112 | +def test_sdpa_backends_disable_cudnn_only_inside_forward(build): |
| 113 | + flag = torch.backends.cuda.cudnn_sdp_enabled() |
| 114 | + model = build({"sdpa_backends": ["flash", "efficient", "math"]}) |
| 115 | + assert torch.backends.cuda.cudnn_sdp_enabled() == flag # construction changed nothing |
| 116 | + _run(model, 2) |
| 117 | + assert model.llm.model.eager_calls[-1]["cudnn"] is False |
| 118 | + assert torch.backends.cuda.cudnn_sdp_enabled() == flag # restored on return |
| 119 | + |
| 120 | + |
| 121 | +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device") |
| 122 | +def test_torch_compile_wraps_cuda_llm_and_keeps_batch_one_eager(build): |
| 123 | + model = build({"torch_compile": True}).cuda() # built on the CPU and moved, as the trainer does |
| 124 | + decoder = model.llm.model |
| 125 | + assert "forward" in decoder.__dict__ |
| 126 | + _run(model, 1) |
| 127 | + assert [c["batch"] for c in decoder.eager_calls] == [1] |
| 128 | + out = _run(model, 2) # compiled: the stand-in does not record under Dynamo |
| 129 | + assert [c["batch"] for c in decoder.eager_calls] == [1] |
| 130 | + torch.testing.assert_close(out, decoder.proj(torch.zeros(2, 3, 8, device=out.device))) |
| 131 | + |
| 132 | + |
| 133 | +def test_torch_compile_keeps_cpu_decoder_eager(build): |
| 134 | + model = build({"torch_compile": True}) |
| 135 | + _run(model, 1) |
| 136 | + _run(model, 4) |
| 137 | + assert [c["batch"] for c in model.llm.model.eager_calls] == [1, 4] |
| 138 | + |
| 139 | + |
| 140 | +def test_recipe_declares_the_torch_floor_its_options_need(): |
| 141 | + """sdpa_backends goes through torch.nn.attention, absent before torch 2.3; if a recipe |
| 142 | + turns it on, the example's requirements.txt has to say so.""" |
| 143 | + for recipe in ("finetune.sh", "lora_finetune.sh"): |
| 144 | + path = os.path.join(RECIPE_DIR, recipe) |
| 145 | + if not os.path.exists(path): |
| 146 | + continue |
| 147 | + with open(path) as f: |
| 148 | + if "llm_conf.sdpa_backends" not in f.read(): |
| 149 | + continue |
| 150 | + with open(os.path.join(RECIPE_DIR, "requirements.txt")) as f: |
| 151 | + declared = re.search(r"^torch>=(\d+)\.(\d+)", f.read(), re.M) |
| 152 | + assert declared, f"{recipe} sets sdpa_backends but requirements.txt pins no torch floor" |
| 153 | + floor = (int(declared.group(1)), int(declared.group(2))) |
| 154 | + assert floor >= (2, 3), f"{recipe} sets sdpa_backends; torch floor is {floor}, needs >= 2.3" |
0 commit comments