Samrish2009 commited on
Commit
8443cd4
·
verified ·
1 Parent(s): d237d26

Deploy SAM-AI model_loader.py

Browse files
Files changed (1) hide show
  1. model_loader.py +298 -0
model_loader.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SAM-AI ZeroGPU Model Loader & Inference Engine
3
+ =============================================
4
+ Manages lifecycle for DeepSeek-R1-Distill-Qwen-7B and verified SAM-AI LoRA adapter
5
+ under Hugging Face Spaces ZeroGPU infrastructure.
6
+
7
+ Strict Invariants:
8
+ 1. Zero third-party commercial LLM routing.
9
+ 2. Cryptographic SHA-256 verification of all adapter weights.
10
+ 3. Fail-closed error handling when weights or memory fail.
11
+ 4. Compliance with ZeroGPU module-level CUDA placement and @spaces.GPU lifecycle.
12
+ """
13
+
14
+ import os
15
+ import sys
16
+ import json
17
+ import time
18
+ import hashlib
19
+ import threading
20
+ from pathlib import Path
21
+ from typing import Dict, Any, Generator, Optional, Tuple
22
+
23
+ # Graceful import of spaces for ZeroGPU environments
24
+ try:
25
+ import spaces
26
+ if not hasattr(spaces, "GPU"):
27
+ raise ImportError("Imported local directory instead of Hugging Face ZeroGPU spaces package.")
28
+ IS_ZEROGPU_ENVIRONMENT = True
29
+ except (ImportError, AttributeError):
30
+ IS_ZEROGPU_ENVIRONMENT = False
31
+ class MockSpaces:
32
+ @staticmethod
33
+ def GPU(func=None, duration=60, size="large"):
34
+ if func is None:
35
+ def decorator(f):
36
+ return f
37
+ return decorator
38
+ return func
39
+ spaces = MockSpaces()
40
+
41
+
42
+ # Official expected SHA-256 hashes from SAM-AI Experiment 001 verification
43
+ EXPECTED_ADAPTER_HASHES: Dict[str, str] = {
44
+ "adapter_config.json": "b300d2ef2c2109badba158aa20906bab58fbb7bfe33431cc0b701a94bc568987",
45
+ "adapter_model.safetensors": "8dcade02a399aa8c308ae63f1881f81b77d7aa9ec128d2fb1cb4b67237d5a986",
46
+ "chat_template.jinja": "56a1447ad31926fdc21fb07e56e5642bd9c850c4f52d8c8af7bbe5f079a84f5f",
47
+ "README.md": "2913618d373b3ab2a6d18364a4aa6e90953fac2b8e05fd43c2d225589c4fadbc",
48
+ "tokenizer.json": "c0d44f762212e3cd7f1a9ce05bf1234124950fc2c3ceb9622772cccb492e27eb",
49
+ "tokenizer_config.json": "8fe0cfd79c4359136c5e2b8d2ce21de8796c1f3e1ee4be6c3fbfd59fc9a4e99c",
50
+ }
51
+
52
+ BASE_MODEL_NAME = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
53
+
54
+
55
+ class ModelLifecycleStatus:
56
+ NOT_INITIALIZED = "NOT_INITIALIZED"
57
+ VERIFYING_ARTIFACTS = "VERIFYING_ARTIFACTS"
58
+ LOADING_BASE_MODEL = "LOADING_BASE_MODEL"
59
+ ATTACHING_ADAPTER = "ATTACHING_ADAPTER"
60
+ READY = "READY"
61
+ ERROR = "ERROR"
62
+
63
+
64
+ class SamAiModelEngine:
65
+ def __init__(self, adapter_dir: Optional[str] = None):
66
+ self.status = ModelLifecycleStatus.NOT_INITIALIZED
67
+ self.status_detail = "Model engine created, awaiting initialization."
68
+ self.base_model_name = BASE_MODEL_NAME
69
+ # The Experiment 001 adapter was rejected. Only load adapter if explicitly requested or enabled.
70
+ load_adapter_env = os.environ.get("SAM_AI_LOAD_ADAPTER", "false").lower()
71
+ if adapter_dir is not None:
72
+ self.adapter_dir = adapter_dir
73
+ elif load_adapter_env in ("true", "1", "yes"):
74
+ self.adapter_dir = self._discover_adapter_dir()
75
+ else:
76
+ self.adapter_dir = None
77
+ self.tokenizer = None
78
+ self.model = None
79
+ self.is_loaded = False
80
+ self.device = "cpu"
81
+ self.verified_adapter_hashes = {}
82
+ self.initialization_error = None
83
+
84
+ def _discover_adapter_dir(self) -> str:
85
+ """Finds the local adapter directory in Space or local workspace."""
86
+ candidates = [
87
+ Path("./adapter"),
88
+ Path("./sam_ai_r1_7b_gsm8k_adapter"),
89
+ Path(__file__).parent / "adapter",
90
+ Path(__file__).parent.parent.parent / "evidence" / "remote_r1_7b_run" / "extracted" / "sam_ai_r1_7b_gsm8k_adapter",
91
+ ]
92
+ for c in candidates:
93
+ if c.exists() and (c / "adapter_model.safetensors").exists():
94
+ return str(c.resolve())
95
+ return "./adapter"
96
+
97
+ def verify_adapter_artifacts(self) -> Tuple[bool, str]:
98
+ """Validates all adapter files against known SHA-256 hashes."""
99
+ adapter_path = Path(self.adapter_dir)
100
+ if not adapter_path.exists():
101
+ return False, f"Adapter directory '{self.adapter_dir}' does not exist."
102
+
103
+ cfg_file = adapter_path / "adapter_config.json"
104
+ if not cfg_file.exists():
105
+ return False, f"Missing adapter_config.json in '{self.adapter_dir}'."
106
+
107
+ try:
108
+ with open(cfg_file, "r", encoding="utf-8") as f:
109
+ cfg_data = json.load(f)
110
+ expected_base = cfg_data.get("base_model_name_or_path")
111
+ if expected_base != BASE_MODEL_NAME:
112
+ return False, f"Adapter base model mismatch: expected '{BASE_MODEL_NAME}', found '{expected_base}'."
113
+ except Exception as e:
114
+ return False, f"Failed to read adapter_config.json: {e}"
115
+
116
+ weights_file = adapter_path / "adapter_model.safetensors"
117
+ if not weights_file.exists():
118
+ return False, f"Missing adapter_model.safetensors in '{self.adapter_dir}'."
119
+
120
+ # Verify checksums for present files
121
+ for filename, expected_hash in EXPECTED_ADAPTER_HASHES.items():
122
+ file_path = adapter_path / filename
123
+ if file_path.exists():
124
+ sha256 = hashlib.sha256()
125
+ with open(file_path, "rb") as f:
126
+ for chunk in iter(lambda: f.read(65536), b""):
127
+ sha256.update(chunk)
128
+ computed_hash = sha256.hexdigest().lower()
129
+ if computed_hash != expected_hash.lower():
130
+ return False, f"Checksum verification failed for {filename}: expected {expected_hash}, got {computed_hash}."
131
+ self.verified_adapter_hashes[filename] = computed_hash
132
+
133
+ return True, "All adapter artifacts verified successfully."
134
+
135
+ def load(self) -> bool:
136
+ """
137
+ Loads base model and (if configured and promoted) LoRA adapter.
138
+ In ZeroGPU, this must be executed at module level.
139
+ """
140
+ if self.adapter_dir is not None:
141
+ self.status = ModelLifecycleStatus.VERIFYING_ARTIFACTS
142
+ ok, msg = self.verify_adapter_artifacts()
143
+ if not ok:
144
+ self.status = ModelLifecycleStatus.ERROR
145
+ self.status_detail = f"Artifact verification failed: {msg}"
146
+ self.initialization_error = msg
147
+ print(f"[FAIL-CLOSED] {self.status_detail}", file=sys.stderr)
148
+ return False
149
+
150
+ try:
151
+ import torch
152
+ from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
153
+ if self.adapter_dir is not None:
154
+ from peft import PeftModel
155
+
156
+ self.status = ModelLifecycleStatus.LOADING_BASE_MODEL
157
+ self.status_detail = f"Loading base model {BASE_MODEL_NAME}..."
158
+ print(f"[*] {self.status_detail}")
159
+
160
+ # Determine device: ZeroGPU provides CUDA emulation at module level
161
+ has_cuda = torch.cuda.is_available()
162
+ self.device = "cuda" if has_cuda else "cpu"
163
+ dtype = torch.bfloat16 if has_cuda else torch.float32
164
+
165
+ self.tokenizer = AutoTokenizer.from_pretrained(
166
+ self.base_model_name,
167
+ trust_remote_code=True
168
+ )
169
+
170
+ # In ZeroGPU, model is moved to cuda at module level
171
+ self.model = AutoModelForCausalLM.from_pretrained(
172
+ self.base_model_name,
173
+ torch_dtype=dtype,
174
+ device_map="auto" if has_cuda else None,
175
+ trust_remote_code=True,
176
+ )
177
+
178
+ if self.adapter_dir is not None:
179
+ self.status = ModelLifecycleStatus.ATTACHING_ADAPTER
180
+ self.status_detail = f"Attaching verified SAM-AI adapter from {self.adapter_dir}..."
181
+ print(f"[*] {self.status_detail}")
182
+ self.model = PeftModel.from_pretrained(self.model, self.adapter_dir)
183
+ self.status_detail = f"Ready: {BASE_MODEL_NAME} + {Path(self.adapter_dir).name} on {self.device}"
184
+ else:
185
+ self.status_detail = f"Ready: {BASE_MODEL_NAME} (Foundation Model) on {self.device}"
186
+
187
+ self.model.eval()
188
+ self.is_loaded = True
189
+ self.status = ModelLifecycleStatus.READY
190
+ print(f"[OK] {self.status_detail}")
191
+ return True
192
+
193
+ except Exception as e:
194
+ self.is_loaded = False
195
+ self.status = ModelLifecycleStatus.ERROR
196
+ self.status_detail = f"Model load failed: {str(e)}"
197
+ self.initialization_error = str(e)
198
+ print(f"[ERROR] {self.status_detail}", file=sys.stderr)
199
+ return False
200
+
201
+ @spaces.GPU(duration=60)
202
+ def generate_stream(
203
+ self,
204
+ messages: list,
205
+ temperature: float = 0.6,
206
+ top_p: float = 0.95,
207
+ max_new_tokens: int = 2048,
208
+ system_prompt: Optional[str] = None
209
+ ) -> Generator[str, None, None]:
210
+ """
211
+ Executes real streaming token generation on ZeroGPU allocation.
212
+ Fails closed with honest error messages if model is unready.
213
+ """
214
+ if not self.is_loaded or self.model is None or self.tokenizer is None:
215
+ err_msg = (
216
+ f"### [SAM-AI Server Not Ready]\n\n"
217
+ f"**Status:** `{self.status}`\n\n"
218
+ f"**Detail:** {self.status_detail}\n\n"
219
+ f"_The model weights or GPU allocation are currently offline. "
220
+ f"SAM-AI never fabricates synthetic responses when inference is unready._"
221
+ )
222
+ yield err_msg
223
+ return
224
+
225
+ try:
226
+ import torch
227
+ from transformers import TextIteratorStreamer
228
+
229
+ # Format conversation using tokenizer chat template
230
+ formatted_messages = []
231
+ if system_prompt:
232
+ formatted_messages.append({"role": "system", "content": system_prompt})
233
+ formatted_messages.extend(messages)
234
+
235
+ try:
236
+ prompt_text = self.tokenizer.apply_chat_template(
237
+ formatted_messages,
238
+ tokenize=False,
239
+ add_generation_prompt=True
240
+ )
241
+ except Exception:
242
+ # Fallback manual format for DeepSeek/Qwen
243
+ prompt_text = ""
244
+ for msg in formatted_messages:
245
+ prompt_text += f"<|im_start|>{msg['role']}\n{msg['content']}<|im_end|>\n"
246
+ prompt_text += "<|im_start|>assistant\n"
247
+
248
+ inputs = self.tokenizer(prompt_text, return_tensors="pt")
249
+ if torch.cuda.is_available():
250
+ inputs = {k: v.to("cuda") for k, v in inputs.items()}
251
+
252
+ streamer = TextIteratorStreamer(
253
+ self.tokenizer,
254
+ skip_prompt=True,
255
+ skip_special_tokens=True
256
+ )
257
+
258
+ gen_kwargs = dict(
259
+ **inputs,
260
+ streamer=streamer,
261
+ max_new_tokens=max_new_tokens,
262
+ temperature=max(0.01, temperature),
263
+ top_p=top_p,
264
+ do_sample=temperature > 0.0,
265
+ pad_token_id=self.tokenizer.eos_token_id,
266
+ )
267
+
268
+ # Run generation in background thread
269
+ thread = threading.Thread(target=self.model.generate, kwargs=gen_kwargs)
270
+ thread.start()
271
+
272
+ accumulated = ""
273
+ for new_text in streamer:
274
+ accumulated += new_text
275
+ yield accumulated
276
+
277
+ thread.join(timeout=65.0)
278
+
279
+ except Exception as e:
280
+ yield f"\n\n**[Generation Error / ZeroGPU Quota Timeout]**: {str(e)}"
281
+
282
+ def get_diagnostics(self) -> Dict[str, Any]:
283
+ """Returns structured diagnostic status without leaking secrets."""
284
+ return {
285
+ "status": self.status,
286
+ "status_detail": self.status_detail,
287
+ "base_model": self.base_model_name,
288
+ "adapter_dir": self.adapter_dir,
289
+ "is_loaded": self.is_loaded,
290
+ "device": self.device,
291
+ "is_zerogpu_environment": IS_ZEROGPU_ENVIRONMENT,
292
+ "verified_adapter_hashes": self.verified_adapter_hashes,
293
+ "initialization_error": self.initialization_error,
294
+ }
295
+
296
+
297
+ # Global singleton instance for Space
298
+ engine = SamAiModelEngine()