ThomsenDrake commited on
Commit
8a7af7a
·
verified ·
1 Parent(s): 9bb7b23

Compact ZeroGPU v14p navigator prompt

Browse files
.env.example CHANGED
@@ -17,10 +17,10 @@ HF_TOKEN=
17
  LLAMA_BASE_URL=http://127.0.0.1:8001/v1
18
  ZEROGPU_MODEL_REPO=build-small-hackathon/figment-finetuned-model-archive
19
  ZEROGPU_MODEL_SUBFOLDER=figment_sft_v14p/figment-sft-v14p-lora-merged-bf16
20
- ZEROGPU_DURATION_SECONDS=120
21
  ZEROGPU_SIZE=large
22
- ZEROGPU_MAX_CONTEXT_TOKENS=16384
23
- ZEROGPU_MAX_GENERATION_TOKENS=1536
24
  FIGMENT_TRACE_DIR=traces
25
  FIGMENT_SMOKE_ALLOW_NETWORK=false
26
  FIGMENT_SMOKE_TIMEOUT_SECONDS=8
 
17
  LLAMA_BASE_URL=http://127.0.0.1:8001/v1
18
  ZEROGPU_MODEL_REPO=build-small-hackathon/figment-finetuned-model-archive
19
  ZEROGPU_MODEL_SUBFOLDER=figment_sft_v14p/figment-sft-v14p-lora-merged-bf16
20
+ ZEROGPU_DURATION_SECONDS=60
21
  ZEROGPU_SIZE=large
22
+ ZEROGPU_MAX_CONTEXT_TOKENS=4096
23
+ ZEROGPU_MAX_GENERATION_TOKENS=768
24
  FIGMENT_TRACE_DIR=traces
25
  FIGMENT_SMOKE_ALLOW_NETWORK=false
26
  FIGMENT_SMOKE_TIMEOUT_SECONDS=8
figment/model_client.py CHANGED
@@ -15,6 +15,7 @@ import wave
15
  from typing import Any
16
 
17
  from .config import FigmentConfig, load_config
 
18
  from .zerogpu_runtime import generate_zero_gpu_json
19
 
20
 
@@ -129,7 +130,7 @@ class ModelClient:
129
  )
130
  if self.config.model_backend == "hf_zerogpu":
131
  return generate_zero_gpu_json(
132
- prompt=prompt,
133
  model_repo=self.config.zerogpu_model_repo,
134
  model_subfolder=self.config.zerogpu_model_subfolder,
135
  model_id=self.config.local_model_id,
@@ -249,6 +250,47 @@ class ModelClient:
249
  return {}
250
 
251
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
  def _timeout_seconds_from_env() -> float:
253
  raw_value = os.getenv(MODEL_TIMEOUT_ENV, "").strip()
254
  if not raw_value:
 
15
  from typing import Any
16
 
17
  from .config import FigmentConfig, load_config
18
+ from .prompt_builder import OUTPUT_SCHEMA, REQUIRED_JSON_SKELETON
19
  from .zerogpu_runtime import generate_zero_gpu_json
20
 
21
 
 
130
  )
131
  if self.config.model_backend == "hf_zerogpu":
132
  return generate_zero_gpu_json(
133
+ prompt=_zero_gpu_compact_prompt(prompt, context),
134
  model_repo=self.config.zerogpu_model_repo,
135
  model_subfolder=self.config.zerogpu_model_subfolder,
136
  model_id=self.config.local_model_id,
 
250
  return {}
251
 
252
 
253
+ ZERO_GPU_SYSTEM_PROMPT = """You are Figment, an offline protocol navigator for a trained responder.
254
+ Use ONLY the compact protocol-card facts in CONTEXT. Return ONLY JSON matching REQUIRED_JSON_SKELETON.
255
+ Do not diagnose, prescribe, dose medication, autonomously triage, discharge, or downgrade deterministic red flags.
256
+ Every candidate_protocol_pathways item must cite a retrieved clinical card_id. source_cards must cite every card used.
257
+ If information is missing or uncertain, list it instead of inventing it."""
258
+
259
+
260
+ def _zero_gpu_compact_prompt(prompt: str, context: dict[str, Any]) -> str:
261
+ if not context:
262
+ return prompt
263
+ compact_context = {
264
+ "structured_intake": context.get("intake", {}),
265
+ "deterministic_red_flags": context.get("rule_results", []),
266
+ "protocol_urgency_floor": context.get("urgency_floor", "routine"),
267
+ "retrieved_protocol_cards": [
268
+ _compact_protocol_card(item.get("card", item)) for item in context.get("retrieved_cards", [])[:6]
269
+ ],
270
+ "navigator_output_schema": OUTPUT_SCHEMA,
271
+ }
272
+ return (
273
+ f"{ZERO_GPU_SYSTEM_PROMPT}\n\n"
274
+ f"REQUIRED_JSON_SKELETON:\n{json.dumps(REQUIRED_JSON_SKELETON, sort_keys=True, separators=(',', ':'))}\n\n"
275
+ f"CONTEXT:\n{json.dumps(compact_context, sort_keys=True, separators=(',', ':'))}"
276
+ )
277
+
278
+
279
+ def _compact_protocol_card(card: dict[str, Any]) -> dict[str, Any]:
280
+ kept_fields = (
281
+ "card_id",
282
+ "title",
283
+ "applies_to",
284
+ "required_observations",
285
+ "red_flags",
286
+ "escalation_criteria",
287
+ "local_actions",
288
+ "forbidden_actions",
289
+ "safety_boundary",
290
+ )
291
+ return {field: card.get(field) for field in kept_fields if card.get(field)}
292
+
293
+
294
  def _timeout_seconds_from_env() -> float:
295
  raw_value = os.getenv(MODEL_TIMEOUT_ENV, "").strip()
296
  if not raw_value:
figment/zerogpu_runtime.py CHANGED
@@ -29,7 +29,7 @@ _RUNTIME_LOCK = threading.Lock()
29
 
30
 
31
  @spaces.GPU(
32
- duration=int(os.getenv("ZEROGPU_DURATION_SECONDS", "120")),
33
  size=os.getenv("ZEROGPU_SIZE", "large"),
34
  )
35
  def generate_zero_gpu_json(
@@ -61,8 +61,8 @@ class _ZeroGpuRuntime:
61
  from transformers import AutoTokenizer
62
 
63
  self.model_id = model_id
64
- self.max_context_tokens = int(os.getenv("ZEROGPU_MAX_CONTEXT_TOKENS", "16384"))
65
- self.max_generation_tokens = int(os.getenv("ZEROGPU_MAX_GENERATION_TOKENS", "1536"))
66
  self.lock = threading.Lock()
67
  self.torch = torch
68
  self.tokenizer = AutoTokenizer.from_pretrained(
@@ -109,6 +109,10 @@ class _ZeroGpuRuntime:
109
  attention_mask = self.torch.ones_like(input_ids)
110
  else:
111
  attention_mask = attention_mask.to(device)
 
 
 
 
112
  input_len = int(input_ids.shape[-1])
113
  available_tokens = max(1, self.max_context_tokens - input_len - 8)
114
  max_new_tokens = max(1, min(self.max_generation_tokens, available_tokens))
 
29
 
30
 
31
  @spaces.GPU(
32
+ duration=int(os.getenv("ZEROGPU_DURATION_SECONDS", "60")),
33
  size=os.getenv("ZEROGPU_SIZE", "large"),
34
  )
35
  def generate_zero_gpu_json(
 
61
  from transformers import AutoTokenizer
62
 
63
  self.model_id = model_id
64
+ self.max_context_tokens = int(os.getenv("ZEROGPU_MAX_CONTEXT_TOKENS", "4096"))
65
+ self.max_generation_tokens = int(os.getenv("ZEROGPU_MAX_GENERATION_TOKENS", "768"))
66
  self.lock = threading.Lock()
67
  self.torch = torch
68
  self.tokenizer = AutoTokenizer.from_pretrained(
 
109
  attention_mask = self.torch.ones_like(input_ids)
110
  else:
111
  attention_mask = attention_mask.to(device)
112
+ max_input_tokens = max(1, self.max_context_tokens - self.max_generation_tokens - 8)
113
+ if int(input_ids.shape[-1]) > max_input_tokens:
114
+ input_ids = input_ids[:, -max_input_tokens:]
115
+ attention_mask = attention_mask[:, -max_input_tokens:]
116
  input_len = int(input_ids.shape[-1])
117
  available_tokens = max(1, self.max_context_tokens - input_len - 8)
118
  max_new_tokens = max(1, min(self.max_generation_tokens, available_tokens))
tests/test_model_client.py CHANGED
@@ -6,7 +6,7 @@ from figment import config as config_module
6
  from figment.config import FigmentConfig
7
  import pytest
8
 
9
- from figment.model_client import ModelClient, ModelClientError
10
 
11
 
12
  EXPECTED_NVIDIA_OMNI_API_MODEL_ID = "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning"
@@ -177,6 +177,37 @@ def test_hf_zerogpu_backend_uses_published_v14p_runtime(monkeypatch: Any) -> Non
177
  }
178
 
179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  def test_custom_hf_endpoint_prefers_hf_token_over_nvidia_key(monkeypatch: Any) -> None:
181
  captured: dict[str, Any] = {}
182
 
 
6
  from figment.config import FigmentConfig
7
  import pytest
8
 
9
+ from figment.model_client import ModelClient, ModelClientError, _zero_gpu_compact_prompt
10
 
11
 
12
  EXPECTED_NVIDIA_OMNI_API_MODEL_ID = "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning"
 
177
  }
178
 
179
 
180
+ def test_hf_zerogpu_compact_prompt_preserves_route_facts_without_verbose_card_text() -> None:
181
+ prompt = "VERBOSE " * 5000
182
+ compact = _zero_gpu_compact_prompt(
183
+ prompt,
184
+ {
185
+ "intake": {"confirmed": True, "chief_concern": "vomiting"},
186
+ "rule_results": [],
187
+ "urgency_floor": "routine",
188
+ "retrieved_cards": [
189
+ {
190
+ "card": {
191
+ "card_id": "PED-DEHYD-RED-FLAGS-v1",
192
+ "title": "Pediatric dehydration red flags",
193
+ "required_observations": ["mental status", "urine output"],
194
+ "red_flags": ["lethargy"],
195
+ "escalation_criteria": ["Any listed red flag requires urgent escalation."],
196
+ "source_note": "omit this verbose provenance field",
197
+ }
198
+ }
199
+ ],
200
+ },
201
+ )
202
+
203
+ assert len(compact) < 5000
204
+ assert "PED-DEHYD-RED-FLAGS-v1" in compact
205
+ assert "chief_concern" in compact
206
+ assert "REQUIRED_JSON_SKELETON" in compact
207
+ assert "source_note" not in compact
208
+ assert "VERBOSE" not in compact
209
+
210
+
211
  def test_custom_hf_endpoint_prefers_hf_token_over_nvidia_key(monkeypatch: Any) -> None:
212
  captured: dict[str, Any] = {}
213