kilat 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kilat/__init__.py +39 -0
- kilat/assurance/__init__.py +67 -0
- kilat/assurance/chaos/__init__.py +30 -0
- kilat/assurance/chaos/hf_scenarios.py +438 -0
- kilat/assurance/chaos/saboteur.py +358 -0
- kilat/assurance/chaos/scenarios.py +443 -0
- kilat/assurance/flight_recorder.py +367 -0
- kilat/assurance/gates/__init__.py +19 -0
- kilat/assurance/gates/gate0_security.py +249 -0
- kilat/assurance/gates/gate1_theory.py +209 -0
- kilat/assurance/gates/gate2_numerical.py +355 -0
- kilat/assurance/gates/gate3_equivalence.py +261 -0
- kilat/assurance/gates/gate4_data.py +253 -0
- kilat/assurance/gates/gate5_dynamics.py +272 -0
- kilat/assurance/gates/gate6_system.py +329 -0
- kilat/assurance/project_rules.py +112 -0
- kilat/assurance/quality.py +231 -0
- kilat/assurance/runner.py +238 -0
- kilat/assurance/scaling.py +215 -0
- kilat/assurance/types.py +193 -0
- kilat/benchmarking/__init__.py +17 -0
- kilat/benchmarking/__main__.py +12 -0
- kilat/benchmarking/arms.py +135 -0
- kilat/benchmarking/benchmark_config.py +284 -0
- kilat/benchmarking/benchmark_runner.py +248 -0
- kilat/benchmarking/component_numerics.py +125 -0
- kilat/benchmarking/harness.py +102 -0
- kilat/benchmarking/loss_ablation.py +162 -0
- kilat/benchmarking/mqar_benchmark.py +248 -0
- kilat/benchmarking/pillars/__init__.py +19 -0
- kilat/benchmarking/pillars/p1_correctness.py +189 -0
- kilat/benchmarking/pillars/p2_capability.py +228 -0
- kilat/benchmarking/pillars/p3_scaling.py +269 -0
- kilat/benchmarking/pillars/p4_efficiency.py +175 -0
- kilat/benchmarking/pillars/p5_diagnostics.py +342 -0
- kilat/benchmarking/plots.py +101 -0
- kilat/benchmarking/protocol.py +101 -0
- kilat/benchmarking/recipe.py +41 -0
- kilat/benchmarking/registry.py +244 -0
- kilat/benchmarking/reporter.py +192 -0
- kilat/benchmarking/results.py +107 -0
- kilat/benchmarking/stability.py +72 -0
- kilat/benchmarking/tasks/__init__.py +13 -0
- kilat/benchmarking/tasks/induction_heads.py +130 -0
- kilat/benchmarking/tasks/mqar.py +162 -0
- kilat/benchmarking/tasks/selective_copying.py +125 -0
- kilat/benchmarking/time_to_quality.py +145 -0
- kilat/cli.py +782 -0
- kilat/configs/__init__.py +19 -0
- kilat/configs/base.py +99 -0
- kilat/configs/dataloader_config.py +332 -0
- kilat/configs/main_config.py +855 -0
- kilat/configs/model_config.py +579 -0
- kilat/configs/tokenizer_config.py +726 -0
- kilat/configs/training_config.py +473 -0
- kilat/data/__init__.py +47 -0
- kilat/data/collator.py +145 -0
- kilat/data/dataloader.py +508 -0
- kilat/data/dataset.py +1210 -0
- kilat/data/preprocess.py +620 -0
- kilat/data/sft.py +277 -0
- kilat/data/tokenizer.py +677 -0
- kilat/distillation/__init__.py +25 -0
- kilat/distillation/losses.py +317 -0
- kilat/distillation/student.py +70 -0
- kilat/distillation/teacher.py +71 -0
- kilat/engine/__init__.py +157 -0
- kilat/engine/args.py +352 -0
- kilat/engine/callbacks.py +550 -0
- kilat/engine/checkpoint.py +1049 -0
- kilat/engine/distributed.py +131 -0
- kilat/engine/integrations.py +1089 -0
- kilat/engine/memory.py +386 -0
- kilat/engine/optimizer.py +322 -0
- kilat/engine/relay.py +290 -0
- kilat/engine/scheduler.py +931 -0
- kilat/engine/sft_trainer.py +149 -0
- kilat/engine/trainer.py +1395 -0
- kilat/inference/__init__.py +143 -0
- kilat/inference/beam_search.py +599 -0
- kilat/inference/export_hf.py +814 -0
- kilat/inference/generation_config.py +371 -0
- kilat/inference/generation_mixin.py +687 -0
- kilat/inference/generator.py +470 -0
- kilat/inference/logit_processor.py +869 -0
- kilat/inference/sampler.py +1032 -0
- kilat/inference/stopping_criteria.py +900 -0
- kilat/inference/templates/modeling_kilat_hub.py +1491 -0
- kilat/integrations/__init__.py +11 -0
- kilat/integrations/huggingface/__init__.py +72 -0
- kilat/integrations/huggingface/configuration_kilat.py +167 -0
- kilat/integrations/huggingface/data.py +118 -0
- kilat/integrations/huggingface/modeling_kilat.py +65 -0
- kilat/integrations/huggingface/peft.py +111 -0
- kilat/integrations/huggingface/trl.py +190 -0
- kilat/integrations/serving/__init__.py +24 -0
- kilat/integrations/serving/openai_server.py +204 -0
- kilat/integrations/serving/schemas.py +109 -0
- kilat/models/__init__.py +55 -0
- kilat/models/attention.py +592 -0
- kilat/models/base.py +1165 -0
- kilat/models/blocks.py +343 -0
- kilat/models/decay.py +214 -0
- kilat/models/ffn.py +674 -0
- kilat/models/kernels/__init__.py +45 -0
- kilat/models/kernels/chunked_ce.py +550 -0
- kilat/models/kernels/flash_decay.py +1121 -0
- kilat/models/kernels/flash_mla.py +799 -0
- kilat/models/kernels/swiglu.py +231 -0
- kilat/models/loading.py +87 -0
- kilat/models/mla.py +378 -0
- kilat/models/norm.py +54 -0
- kilat/models/rope.py +493 -0
- kilat/models/transformer.py +892 -0
- kilat/utils/__init__.py +70 -0
- kilat/utils/banner.py +38 -0
- kilat/utils/base_model.py +34 -0
- kilat/utils/report.py +111 -0
- kilat/utils/security.py +138 -0
- kilat/utils/validators.py +451 -0
- kilat-2.0.0.dist-info/METADATA +368 -0
- kilat-2.0.0.dist-info/RECORD +126 -0
- kilat-2.0.0.dist-info/WHEEL +5 -0
- kilat-2.0.0.dist-info/entry_points.txt +2 -0
- kilat-2.0.0.dist-info/licenses/LICENSE +201 -0
- kilat-2.0.0.dist-info/top_level.txt +1 -0
kilat/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
__version__ = "2.0.0"
|
|
2
|
+
|
|
3
|
+
from kilat.models.transformer import KilatTransformer
|
|
4
|
+
from kilat.configs.main_config import MainConfig
|
|
5
|
+
from kilat.configs.model_config import KilatConfig
|
|
6
|
+
from kilat.engine.trainer import KilatTrainer
|
|
7
|
+
from kilat.engine.sft_trainer import KilatSFTTrainer
|
|
8
|
+
from kilat.engine.args import TrainingArguments
|
|
9
|
+
from kilat.engine.distributed import DistributedContext
|
|
10
|
+
from kilat.data.dataset import PretrainingDataset
|
|
11
|
+
from kilat.data.dataloader import (
|
|
12
|
+
build_dataloaders_from_config,
|
|
13
|
+
build_eval_dataloader,
|
|
14
|
+
build_train_dataloader,
|
|
15
|
+
)
|
|
16
|
+
from kilat.data.collator import KilatDataCollator
|
|
17
|
+
from kilat.data.sft import SFTDataCollator, SFTDataset
|
|
18
|
+
from kilat.inference.generation_config import GenerationConfig
|
|
19
|
+
from kilat.inference.generator import TextGenerator
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"__version__",
|
|
23
|
+
"KilatTransformer",
|
|
24
|
+
"MainConfig",
|
|
25
|
+
"KilatConfig",
|
|
26
|
+
"KilatTrainer",
|
|
27
|
+
"KilatSFTTrainer",
|
|
28
|
+
"TrainingArguments",
|
|
29
|
+
"DistributedContext",
|
|
30
|
+
"PretrainingDataset",
|
|
31
|
+
"build_train_dataloader",
|
|
32
|
+
"build_eval_dataloader",
|
|
33
|
+
"build_dataloaders_from_config",
|
|
34
|
+
"KilatDataCollator",
|
|
35
|
+
"SFTDataCollator",
|
|
36
|
+
"SFTDataset",
|
|
37
|
+
"GenerationConfig",
|
|
38
|
+
"TextGenerator",
|
|
39
|
+
]
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from kilat.assurance.chaos import (
|
|
4
|
+
ALL_SCENARIO_IDS,
|
|
5
|
+
ALL_HF_SCENARIO_IDS,
|
|
6
|
+
ChaosScenarioResult,
|
|
7
|
+
ChaosSuiteReport,
|
|
8
|
+
HFChaosScenarioResult,
|
|
9
|
+
HFChaosSuiteReport,
|
|
10
|
+
HuggingFaceChaosSaboteur,
|
|
11
|
+
Saboteur,
|
|
12
|
+
SimulatedPreemptionError,
|
|
13
|
+
run_chaos_suite,
|
|
14
|
+
run_hf_chaos_suite,
|
|
15
|
+
)
|
|
16
|
+
from kilat.assurance.flight_recorder import (
|
|
17
|
+
FlightRecorderCallback,
|
|
18
|
+
TrainingDivergedError,
|
|
19
|
+
)
|
|
20
|
+
from kilat.assurance.gates import (
|
|
21
|
+
run_gate1_theory,
|
|
22
|
+
run_gate2_numerical,
|
|
23
|
+
run_gate3_equivalence,
|
|
24
|
+
run_gate4_data,
|
|
25
|
+
run_gate5_dynamics,
|
|
26
|
+
run_gate6_system,
|
|
27
|
+
)
|
|
28
|
+
from kilat.assurance.runner import run_verification_pipeline
|
|
29
|
+
from kilat.assurance.scaling import (
|
|
30
|
+
run_stage7_scaling_harness,
|
|
31
|
+
run_stage8_readiness_signoff,
|
|
32
|
+
)
|
|
33
|
+
from kilat.assurance.types import (
|
|
34
|
+
AssuranceError,
|
|
35
|
+
AssuranceFailureCode,
|
|
36
|
+
AssuranceReport,
|
|
37
|
+
GateResult,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
"ALL_SCENARIO_IDS",
|
|
42
|
+
"ALL_HF_SCENARIO_IDS",
|
|
43
|
+
"AssuranceError",
|
|
44
|
+
"AssuranceFailureCode",
|
|
45
|
+
"AssuranceReport",
|
|
46
|
+
"ChaosScenarioResult",
|
|
47
|
+
"ChaosSuiteReport",
|
|
48
|
+
"FlightRecorderCallback",
|
|
49
|
+
"GateResult",
|
|
50
|
+
"HFChaosScenarioResult",
|
|
51
|
+
"HFChaosSuiteReport",
|
|
52
|
+
"HuggingFaceChaosSaboteur",
|
|
53
|
+
"Saboteur",
|
|
54
|
+
"SimulatedPreemptionError",
|
|
55
|
+
"TrainingDivergedError",
|
|
56
|
+
"run_chaos_suite",
|
|
57
|
+
"run_hf_chaos_suite",
|
|
58
|
+
"run_gate1_theory",
|
|
59
|
+
"run_gate2_numerical",
|
|
60
|
+
"run_gate3_equivalence",
|
|
61
|
+
"run_gate4_data",
|
|
62
|
+
"run_gate5_dynamics",
|
|
63
|
+
"run_gate6_system",
|
|
64
|
+
"run_stage7_scaling_harness",
|
|
65
|
+
"run_stage8_readiness_signoff",
|
|
66
|
+
"run_verification_pipeline",
|
|
67
|
+
]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from kilat.assurance.chaos.saboteur import Saboteur, SimulatedPreemptionError
|
|
4
|
+
from kilat.assurance.chaos.scenarios import (
|
|
5
|
+
ALL_SCENARIO_IDS,
|
|
6
|
+
ChaosScenarioResult,
|
|
7
|
+
ChaosSuiteReport,
|
|
8
|
+
run_chaos_suite,
|
|
9
|
+
)
|
|
10
|
+
from kilat.assurance.chaos.hf_scenarios import (
|
|
11
|
+
ALL_HF_SCENARIO_IDS,
|
|
12
|
+
HFChaosScenarioResult,
|
|
13
|
+
HFChaosSuiteReport,
|
|
14
|
+
HuggingFaceChaosSaboteur,
|
|
15
|
+
run_hf_chaos_suite,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"ALL_SCENARIO_IDS",
|
|
20
|
+
"ALL_HF_SCENARIO_IDS",
|
|
21
|
+
"ChaosScenarioResult",
|
|
22
|
+
"ChaosSuiteReport",
|
|
23
|
+
"HFChaosScenarioResult",
|
|
24
|
+
"HFChaosSuiteReport",
|
|
25
|
+
"HuggingFaceChaosSaboteur",
|
|
26
|
+
"Saboteur",
|
|
27
|
+
"SimulatedPreemptionError",
|
|
28
|
+
"run_chaos_suite",
|
|
29
|
+
"run_hf_chaos_suite",
|
|
30
|
+
]
|
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Generator, Sequence
|
|
13
|
+
|
|
14
|
+
import torch
|
|
15
|
+
import torch.nn as nn
|
|
16
|
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
17
|
+
from transformers.cache_utils import DynamicCache
|
|
18
|
+
|
|
19
|
+
from kilat.configs.model_config import KilatConfig
|
|
20
|
+
from kilat.inference.export_hf import convert_checkpoint_to_hf
|
|
21
|
+
from kilat.integrations.huggingface.configuration_kilat import KilatConfig as HFKilatConfig
|
|
22
|
+
from kilat.integrations.huggingface.modeling_kilat import KilatForCausalLM as InTreeKilatForCausalLM
|
|
23
|
+
from kilat.integrations.huggingface.peft import DEFAULT_KILAT_LORA_TARGET_MODULES, get_kilat_lora_config
|
|
24
|
+
from kilat.models.transformer import KilatTransformer
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _require(condition: bool, message: str = "") -> None:
|
|
30
|
+
if not condition:
|
|
31
|
+
raise RuntimeError(message or "Invariant requirement violated")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class HFChaosScenarioResult:
|
|
36
|
+
scenario_id: str
|
|
37
|
+
name: str
|
|
38
|
+
caught: bool
|
|
39
|
+
description: str
|
|
40
|
+
duration_ms: float
|
|
41
|
+
details: str = ""
|
|
42
|
+
|
|
43
|
+
def to_dict(self) -> dict[str, Any]:
|
|
44
|
+
return {
|
|
45
|
+
"scenario_id": self.scenario_id,
|
|
46
|
+
"name": self.name,
|
|
47
|
+
"caught": self.caught,
|
|
48
|
+
"description": self.description,
|
|
49
|
+
"duration_ms": round(self.duration_ms, 3),
|
|
50
|
+
"details": self.details,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class HFChaosSuiteReport:
|
|
56
|
+
baseline_passed: bool
|
|
57
|
+
scenarios: list[HFChaosScenarioResult]
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def scenarios_total(self) -> int:
|
|
61
|
+
return len(self.scenarios)
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def scenarios_passed(self) -> int:
|
|
65
|
+
return sum(1 for s in self.scenarios if s.caught)
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def false_negatives(self) -> int:
|
|
69
|
+
return self.scenarios_total - self.scenarios_passed
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def passed(self) -> bool:
|
|
73
|
+
return self.baseline_passed and self.false_negatives == 0
|
|
74
|
+
|
|
75
|
+
def to_dict(self) -> dict[str, Any]:
|
|
76
|
+
return {
|
|
77
|
+
"executed": True,
|
|
78
|
+
"baseline_passed": self.baseline_passed,
|
|
79
|
+
"scenarios_total": self.scenarios_total,
|
|
80
|
+
"scenarios_passed": self.scenarios_passed,
|
|
81
|
+
"false_negatives": self.false_negatives,
|
|
82
|
+
"overall_status": "PASS" if self.passed else "FAIL",
|
|
83
|
+
"scenarios": [s.to_dict() for s in self.scenarios],
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
ALL_HF_SCENARIO_IDS = (
|
|
88
|
+
"HFC-01",
|
|
89
|
+
"HFC-02",
|
|
90
|
+
"HFC-03",
|
|
91
|
+
"HFC-04",
|
|
92
|
+
"HFC-05",
|
|
93
|
+
"HFC-06",
|
|
94
|
+
"HFC-07",
|
|
95
|
+
"HFC-08",
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class HuggingFaceChaosSaboteur:
|
|
100
|
+
"""
|
|
101
|
+
100% Non-Destructive In-Memory Fault Injector for Hugging Face Integration Chaos.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
@contextlib.contextmanager
|
|
105
|
+
def inject_dynamic_cache(self, num_layers: int = 2) -> Generator[DynamicCache, None, None]:
|
|
106
|
+
"""Inject a modern HuggingFace DynamicCache object."""
|
|
107
|
+
cache = DynamicCache()
|
|
108
|
+
for _ in range(num_layers):
|
|
109
|
+
cache.update(torch.randn(1, 2, 4, 8), torch.randn(1, 2, 4, 8), 0)
|
|
110
|
+
yield cache
|
|
111
|
+
|
|
112
|
+
@contextlib.contextmanager
|
|
113
|
+
def corrupt_export_auto_map(self, export_dir: Path) -> Generator[Path, None, None]:
|
|
114
|
+
"""Corrupt auto_map in config.json and restore in finally block."""
|
|
115
|
+
cfg_path = export_dir / "config.json"
|
|
116
|
+
with open(cfg_path, "r", encoding="utf-8") as f:
|
|
117
|
+
original = f.read()
|
|
118
|
+
|
|
119
|
+
corrupted = json.loads(original)
|
|
120
|
+
corrupted.pop("auto_map", None)
|
|
121
|
+
with open(cfg_path, "w", encoding="utf-8") as f:
|
|
122
|
+
json.dump(corrupted, f)
|
|
123
|
+
|
|
124
|
+
try:
|
|
125
|
+
yield cfg_path
|
|
126
|
+
finally:
|
|
127
|
+
with open(cfg_path, "w", encoding="utf-8") as f:
|
|
128
|
+
f.write(original)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def run_hf_chaos_suite(scenarios: str | Sequence[str] = "all") -> HFChaosSuiteReport:
|
|
132
|
+
"""
|
|
133
|
+
Execute Hugging Face Integration Chaos Engineering Suite.
|
|
134
|
+
"""
|
|
135
|
+
if isinstance(scenarios, str):
|
|
136
|
+
if scenarios.strip().lower() == "all":
|
|
137
|
+
selected = list(ALL_HF_SCENARIO_IDS)
|
|
138
|
+
else:
|
|
139
|
+
selected = [s.strip().upper() for s in scenarios.split(",") if s.strip()]
|
|
140
|
+
else:
|
|
141
|
+
selected = [s.strip().upper() for s in scenarios]
|
|
142
|
+
|
|
143
|
+
unknown = [s for s in selected if s not in ALL_HF_SCENARIO_IDS]
|
|
144
|
+
if unknown:
|
|
145
|
+
raise ValueError(f"Unknown HF chaos scenario IDs: {unknown}. Valid: {ALL_HF_SCENARIO_IDS}")
|
|
146
|
+
|
|
147
|
+
# Micro configuration for swift in-memory chaos tests
|
|
148
|
+
cfg = KilatConfig(
|
|
149
|
+
vocab_size=128,
|
|
150
|
+
n_embd=64,
|
|
151
|
+
n_head=4,
|
|
152
|
+
n_layer=2,
|
|
153
|
+
max_position_embeddings=64,
|
|
154
|
+
recall_pattern="macro_synergy",
|
|
155
|
+
use_rope=True,
|
|
156
|
+
rope_head_dim=8,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
saboteur = HuggingFaceChaosSaboteur()
|
|
160
|
+
results: list[HFChaosScenarioResult] = []
|
|
161
|
+
|
|
162
|
+
with tempfile.TemporaryDirectory() as base_ckpt_dir, tempfile.TemporaryDirectory() as base_out_dir:
|
|
163
|
+
ckpt_path = Path(base_ckpt_dir)
|
|
164
|
+
out_path = Path(base_out_dir)
|
|
165
|
+
|
|
166
|
+
native_model = KilatTransformer(cfg)
|
|
167
|
+
native_model.eval()
|
|
168
|
+
native_model.save_pretrained(ckpt_path)
|
|
169
|
+
|
|
170
|
+
convert_checkpoint_to_hf(ckpt_path, out_path, skip_validation=True)
|
|
171
|
+
|
|
172
|
+
# Baseline check
|
|
173
|
+
try:
|
|
174
|
+
trust_remote = bool(1)
|
|
175
|
+
hf_model = AutoModelForCausalLM.from_pretrained(out_path, trust_remote_code=trust_remote)
|
|
176
|
+
hf_model.eval()
|
|
177
|
+
prompt = torch.tensor([[1, 10, 20]])
|
|
178
|
+
with torch.no_grad():
|
|
179
|
+
base_gen = hf_model.generate(prompt, max_new_tokens=4, use_cache=False)
|
|
180
|
+
baseline_passed = bool(base_gen.shape == (1, 7))
|
|
181
|
+
except Exception as e:
|
|
182
|
+
logger.error("HF Baseline check failed: %s", e)
|
|
183
|
+
baseline_passed = False
|
|
184
|
+
|
|
185
|
+
for sc_id in selected:
|
|
186
|
+
t0 = time.perf_counter()
|
|
187
|
+
caught = False
|
|
188
|
+
details = ""
|
|
189
|
+
|
|
190
|
+
if sc_id == "HFC-01":
|
|
191
|
+
# Scenario 1: DynamicCache & Foreign Cache Injection Resilience
|
|
192
|
+
desc = "DynamicCache & Foreign Cache Injection Resilience"
|
|
193
|
+
try:
|
|
194
|
+
with saboteur.inject_dynamic_cache(num_layers=cfg.n_layer) as foreign_cache:
|
|
195
|
+
# Direct forward with foreign cache
|
|
196
|
+
out_fwd = hf_model(prompt, past_key_values=foreign_cache)
|
|
197
|
+
# Generate with use_cache=True
|
|
198
|
+
out_gen_true = hf_model.generate(prompt, max_new_tokens=4, use_cache=True)
|
|
199
|
+
# Generate without specifying use_cache (defaults to generation_config)
|
|
200
|
+
out_gen_def = hf_model.generate(prompt, max_new_tokens=4)
|
|
201
|
+
|
|
202
|
+
_require(out_fwd.logits.shape == (1, 3, cfg.vocab_size), "Logit shape mismatch")
|
|
203
|
+
_require(out_gen_true.shape == (1, 7), "Gen true shape mismatch")
|
|
204
|
+
_require(out_gen_def.shape == (1, 7), "Gen def shape mismatch")
|
|
205
|
+
caught = True
|
|
206
|
+
details = "Gracefully handled DynamicCache without subscriptable error."
|
|
207
|
+
except Exception as e:
|
|
208
|
+
caught = False
|
|
209
|
+
details = f"DynamicCache injection crashed: {e}"
|
|
210
|
+
|
|
211
|
+
elif sc_id == "HFC-02":
|
|
212
|
+
# Scenario 2: Bidirectional Schema Drift & Attribute Mutability
|
|
213
|
+
desc = "Bidirectional Schema Drift & Attribute Mutability"
|
|
214
|
+
try:
|
|
215
|
+
hf_cfg = HFKilatConfig(vocab_size=256, n_embd=128, n_layer=4, n_head=8)
|
|
216
|
+
_require(hf_cfg.num_hidden_layers == 4, "Initial layers mismatch")
|
|
217
|
+
_require(hf_cfg.hidden_size == 128, "Initial hidden mismatch")
|
|
218
|
+
_require(hf_cfg.num_attention_heads == 8, "Initial heads mismatch")
|
|
219
|
+
|
|
220
|
+
# Mutate HF standard attributes
|
|
221
|
+
hf_cfg.num_hidden_layers = 6
|
|
222
|
+
hf_cfg.hidden_size = 256
|
|
223
|
+
hf_cfg.num_attention_heads = 16
|
|
224
|
+
|
|
225
|
+
# Assert bidirectional sync
|
|
226
|
+
_require(hf_cfg.n_layer == 6, "n_layer sync failed")
|
|
227
|
+
_require(hf_cfg.n_embd == 256, "n_embd sync failed")
|
|
228
|
+
_require(hf_cfg.n_head == 16, "n_head sync failed")
|
|
229
|
+
|
|
230
|
+
# Assert serialization round-trip
|
|
231
|
+
cfg_dict = hf_cfg.to_dict()
|
|
232
|
+
_require(cfg_dict["num_hidden_layers"] == 6, "dict layers mismatch")
|
|
233
|
+
_require(cfg_dict["hidden_size"] == 256, "dict hidden mismatch")
|
|
234
|
+
_require(cfg_dict["num_attention_heads"] == 16, "dict heads mismatch")
|
|
235
|
+
_require(cfg_dict["attribute_map"]["num_hidden_layers"] == "n_layer", "attribute_map mismatch")
|
|
236
|
+
|
|
237
|
+
caught = True
|
|
238
|
+
details = "Bidirectional property getters/setters & serialization verified."
|
|
239
|
+
except Exception as e:
|
|
240
|
+
caught = False
|
|
241
|
+
details = f"Schema mutability error: {e}"
|
|
242
|
+
|
|
243
|
+
elif sc_id == "HFC-03":
|
|
244
|
+
# Scenario 3: Extreme Adversarial Sampling Parameters
|
|
245
|
+
desc = "Extreme Adversarial Sampling Parameters"
|
|
246
|
+
try:
|
|
247
|
+
params_to_test: list[dict[str, Any]] = [
|
|
248
|
+
{"temperature": 0.0, "do_sample": False},
|
|
249
|
+
{"temperature": 4.0, "do_sample": True},
|
|
250
|
+
{"top_k": 1, "do_sample": True},
|
|
251
|
+
{"top_p": 0.01, "do_sample": True},
|
|
252
|
+
{"repetition_penalty": 2.0, "do_sample": False},
|
|
253
|
+
dict(max_new_tokens=1),
|
|
254
|
+
dict(max_new_tokens=16),
|
|
255
|
+
]
|
|
256
|
+
for p in params_to_test:
|
|
257
|
+
# Explicit length avoids transformers' default-max_length UserWarning.
|
|
258
|
+
gen_out = hf_model.generate(prompt, **(dict(max_new_tokens=4) | p))
|
|
259
|
+
_require(bool(torch.all(gen_out >= 0).item()) and bool(torch.all(gen_out < cfg.vocab_size).item()), "Token out of bounds")
|
|
260
|
+
_require(bool(torch.isfinite(gen_out.float()).all().item()), "Non-finite token output")
|
|
261
|
+
|
|
262
|
+
caught = True
|
|
263
|
+
details = f"Passed {len(params_to_test)} adversarial sampling regimes cleanly."
|
|
264
|
+
except Exception as e:
|
|
265
|
+
caught = False
|
|
266
|
+
details = f"Adversarial sampling crashed: {e}"
|
|
267
|
+
|
|
268
|
+
elif sc_id == "HFC-04":
|
|
269
|
+
# Scenario 4: Asymmetric Batched Left-Padding & Causal Isolation
|
|
270
|
+
desc = "Asymmetric Batched Left-Padding & Causal Isolation"
|
|
271
|
+
try:
|
|
272
|
+
# Batch of 2: sample 1 has 4 tokens, sample 2 has 2 pad tokens + 2 real tokens
|
|
273
|
+
padded_batch = torch.tensor([
|
|
274
|
+
[10, 20, 30, 40],
|
|
275
|
+
[0, 0, 30, 40],
|
|
276
|
+
])
|
|
277
|
+
attn_mask = torch.tensor([
|
|
278
|
+
[1, 1, 1, 1],
|
|
279
|
+
[0, 0, 1, 1],
|
|
280
|
+
])
|
|
281
|
+
batch_gen = hf_model.generate(
|
|
282
|
+
padded_batch,
|
|
283
|
+
attention_mask=attn_mask,
|
|
284
|
+
max_new_tokens=4,
|
|
285
|
+
do_sample=False,
|
|
286
|
+
use_cache=False,
|
|
287
|
+
)
|
|
288
|
+
_require(batch_gen.shape == (2, 8), "Batch shape mismatch")
|
|
289
|
+
_require(bool(torch.all(batch_gen >= 0).item()) and bool(torch.all(batch_gen < cfg.vocab_size).item()), "Batch tokens out of bounds")
|
|
290
|
+
caught = True
|
|
291
|
+
details = "Batched left-padding generated valid non-null outputs."
|
|
292
|
+
except Exception as e:
|
|
293
|
+
caught = False
|
|
294
|
+
details = f"Batched left-padding failed: {e}"
|
|
295
|
+
|
|
296
|
+
elif sc_id == "HFC-05":
|
|
297
|
+
# Scenario 5: Corrupted Export Artifacts & Manifest Detection
|
|
298
|
+
desc = "Corrupted Export Artifacts & AutoMap Detection"
|
|
299
|
+
try:
|
|
300
|
+
with saboteur.corrupt_export_auto_map(out_path):
|
|
301
|
+
with open(out_path / "config.json") as f:
|
|
302
|
+
corrupted_data = json.load(f)
|
|
303
|
+
_require("auto_map" not in corrupted_data, "auto_map not removed")
|
|
304
|
+
|
|
305
|
+
# After restore
|
|
306
|
+
with open(out_path / "config.json") as f:
|
|
307
|
+
restored_data = json.load(f)
|
|
308
|
+
_require("auto_map" in restored_data, "auto_map not restored")
|
|
309
|
+
_require((out_path / "generation_config.json").exists(), "generation_config.json missing")
|
|
310
|
+
caught = True
|
|
311
|
+
details = "AutoMap mutation and recovery verified without residual state."
|
|
312
|
+
except Exception as e:
|
|
313
|
+
caught = False
|
|
314
|
+
details = f"Export corruption test failed: {e}"
|
|
315
|
+
|
|
316
|
+
elif sc_id == "HFC-06":
|
|
317
|
+
# Scenario 6: PEFT LoRA Adaptation & Frozen Base Invariant
|
|
318
|
+
desc = "PEFT LoRA Adaptation & Frozen Base Invariant"
|
|
319
|
+
try:
|
|
320
|
+
import peft
|
|
321
|
+
from peft import get_peft_model
|
|
322
|
+
|
|
323
|
+
lora_cfg = get_kilat_lora_config(
|
|
324
|
+
r=4,
|
|
325
|
+
lora_alpha=8,
|
|
326
|
+
target_modules=["down", "gate", "up"],
|
|
327
|
+
)
|
|
328
|
+
# Wrap in-tree model to verify PEFT adapter compatibility
|
|
329
|
+
dense_peft_cfg = KilatConfig(vocab_size=128, n_embd=64, n_head=4, n_layer=2, ffn_mode="dense")
|
|
330
|
+
in_tree_model = InTreeKilatForCausalLM(dense_peft_cfg)
|
|
331
|
+
peft_model = get_peft_model(in_tree_model, lora_cfg)
|
|
332
|
+
|
|
333
|
+
# Invariant 1: Base weights must be frozen
|
|
334
|
+
base_trainable = [p for n, p in peft_model.named_parameters() if "lora_" not in n and p.requires_grad]
|
|
335
|
+
_require(len(base_trainable) == 0, f"Found unfrozen base weights: {len(base_trainable)}")
|
|
336
|
+
|
|
337
|
+
# Invariant 2: LoRA adapters must be trainable
|
|
338
|
+
lora_trainable = [p for n, p in peft_model.named_parameters() if "lora_" in n and p.requires_grad]
|
|
339
|
+
_require(len(lora_trainable) > 0, "No trainable LoRA weights found")
|
|
340
|
+
|
|
341
|
+
# Invariant 3: Gradients flow on backward
|
|
342
|
+
opt = torch.optim.AdamW(peft_model.parameters(), lr=1e-3)
|
|
343
|
+
loss = peft_model(prompt, labels=prompt).loss
|
|
344
|
+
loss.backward()
|
|
345
|
+
_require(all(p.grad is not None and torch.isfinite(p.grad).all() for p in lora_trainable), "Gradients non-finite or missing")
|
|
346
|
+
|
|
347
|
+
caught = True
|
|
348
|
+
details = f"LoRA successfully attached ({len(lora_trainable)} adapter tensors, 0 base unfrozen)."
|
|
349
|
+
except ImportError:
|
|
350
|
+
# If peft is not installed in the environment, verify graceful guard
|
|
351
|
+
try:
|
|
352
|
+
get_kilat_lora_config()
|
|
353
|
+
except ImportError as err:
|
|
354
|
+
if "pip install peft" in str(err):
|
|
355
|
+
caught = True
|
|
356
|
+
details = "PEFT missing guard verified: raised clear installation instructions."
|
|
357
|
+
else:
|
|
358
|
+
caught = False
|
|
359
|
+
details = f"Unexpected error message: {err}"
|
|
360
|
+
except Exception as e:
|
|
361
|
+
caught = False
|
|
362
|
+
details = f"PEFT LoRA validation failed: {e}"
|
|
363
|
+
|
|
364
|
+
elif sc_id == "HFC-07":
|
|
365
|
+
# Scenario 7: Boundary Loss & All-Masked -100 Invariant
|
|
366
|
+
desc = "Boundary Loss & All-Masked -100 Invariant"
|
|
367
|
+
try:
|
|
368
|
+
all_masked_labels = torch.full_like(prompt, -100)
|
|
369
|
+
out = hf_model(prompt, labels=all_masked_labels)
|
|
370
|
+
# When all tokens are masked, cross-entropy is zero.
|
|
371
|
+
# Total loss is finite and non-negative (may contain auxiliary router loss).
|
|
372
|
+
_require(out.loss is not None, "Loss is None")
|
|
373
|
+
_require(bool(torch.isfinite(out.loss).item()), "Loss is non-finite")
|
|
374
|
+
_require(float(out.loss.item()) >= 0.0, "Loss is negative")
|
|
375
|
+
|
|
376
|
+
# Also test with dense model (no aux loss) where loss must be strictly 0.0
|
|
377
|
+
dense_cfg = KilatConfig(vocab_size=128, n_embd=64, n_head=4, n_layer=2, ffn_mode="dense")
|
|
378
|
+
dense_model = KilatTransformer(dense_cfg)
|
|
379
|
+
dense_out = dense_model(prompt, labels=all_masked_labels)
|
|
380
|
+
_require(dense_out.loss is not None, "Dense loss is None")
|
|
381
|
+
_require(float(dense_out.loss.item()) == 0.0, "Dense loss not zero")
|
|
382
|
+
|
|
383
|
+
caught = True
|
|
384
|
+
details = f"All-masked labels produced finite loss (dense: {dense_out.loss.item():.4f}, moe: {out.loss.item():.4f}) without NaN/Inf."
|
|
385
|
+
except Exception as e:
|
|
386
|
+
caught = False
|
|
387
|
+
details = f"All-masked labels test failed: {e}"
|
|
388
|
+
|
|
389
|
+
elif sc_id == "HFC-08":
|
|
390
|
+
# Scenario 8: Multithreaded Streaming Generation & Early Cancellation
|
|
391
|
+
desc = "Multithreaded Streaming Generation & Early Cancellation"
|
|
392
|
+
try:
|
|
393
|
+
from transformers import TextIteratorStreamer
|
|
394
|
+
|
|
395
|
+
# Mock tokenizer with simple decoding
|
|
396
|
+
class MockTokenizer:
|
|
397
|
+
def decode(self, ids: Sequence[int], skip_special_tokens: bool = True) -> str:
|
|
398
|
+
return f"tok_{ids[0]}" if len(ids) == 1 else " ".join(f"tok_{i}" for i in ids)
|
|
399
|
+
|
|
400
|
+
streamer = TextIteratorStreamer(MockTokenizer(), skip_prompt=True)
|
|
401
|
+
gen_kwargs = {
|
|
402
|
+
"input_ids": prompt,
|
|
403
|
+
"streamer": streamer,
|
|
404
|
+
"max_new_tokens": 8,
|
|
405
|
+
"do_sample": False,
|
|
406
|
+
}
|
|
407
|
+
t = threading.Thread(target=hf_model.generate, kwargs=gen_kwargs)
|
|
408
|
+
t.start()
|
|
409
|
+
|
|
410
|
+
collected = []
|
|
411
|
+
for idx, token_text in enumerate(streamer):
|
|
412
|
+
collected.append(token_text)
|
|
413
|
+
if idx >= 2:
|
|
414
|
+
# Early cancellation / break
|
|
415
|
+
break
|
|
416
|
+
|
|
417
|
+
t.join(timeout=5.0)
|
|
418
|
+
_require(not t.is_alive(), "Generation thread hung after streamer break")
|
|
419
|
+
_require(len(collected) >= 3, "Streamer yielded fewer than 3 tokens")
|
|
420
|
+
caught = True
|
|
421
|
+
details = f"Streamer successfully pulled {len(collected)} tokens and thread joined cleanly."
|
|
422
|
+
except Exception as e:
|
|
423
|
+
caught = False
|
|
424
|
+
details = f"Streaming thread test failed: {e}"
|
|
425
|
+
|
|
426
|
+
elapsed = (time.perf_counter() - t0) * 1000.0
|
|
427
|
+
results.append(
|
|
428
|
+
HFChaosScenarioResult(
|
|
429
|
+
scenario_id=sc_id,
|
|
430
|
+
name=desc,
|
|
431
|
+
caught=caught,
|
|
432
|
+
description=desc,
|
|
433
|
+
duration_ms=elapsed,
|
|
434
|
+
details=details,
|
|
435
|
+
)
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
return HFChaosSuiteReport(baseline_passed=baseline_passed, scenarios=results)
|