dmontgomery40 commited on
Commit
e9ee6ad
·
verified ·
1 Parent(s): ee600ac

Sync from GitHub via hub-sync

Browse files
deploy/huggingface/app.py CHANGED
@@ -12,9 +12,14 @@ from fastapi.responses import HTMLResponse, JSONResponse
12
  from fastapi.staticfiles import StaticFiles
13
  from deploy.huggingface.pretrained import MODEL_ID
14
 
15
- MODELS = (MODEL_ID,)
16
- SESSIONS = ('demo_text',)
17
  MAX_BODY = 8192
 
 
 
 
 
 
 
18
 
19
 
20
  def _integer(value, low, high):
@@ -43,18 +48,98 @@ def _valid_body(action, body):
43
  return False
44
 
45
 
46
- # what the shared demo lets a visitor do; the UI renders exactly this set
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  PUBLIC_CAPABILITIES = {'create_session': False, 'fork': False, 'reset': True, 'delete': False, 'resume': True, 'calibrate': False, 'sleep': False}
48
 
49
 
50
  class PublicDemoGate:
51
- """Expose the fixed text playground without changing the local research API."""
52
- def __init__(self, app, store=None, device='cpu'):
 
 
 
53
  self.app = app
54
  self.store = store
55
  self.device = device
 
56
  self.busy = asyncio.Lock()
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  async def __call__(self, scope, receive, send):
59
  if scope['type'] != 'http' or not scope['path'].startswith('/api'):
60
  return await self.app(scope, receive, send)
@@ -63,32 +148,40 @@ class PublicDemoGate:
63
  async def reject(status, message):
64
  await JSONResponse({'detail': message}, status_code=status)(scope, receive, send)
65
 
 
 
 
 
 
66
  reads = ('/api/health', '/api/models', '/api/sessions')
67
  session_read = re.fullmatch(r'/api/sessions/([^/]+)(?:/(state|transactions))?', path)
68
- session_read = session_read and session_read.group(1) in SESSIONS
69
  model_read = re.fullmatch(r'/api/models/([^/]+)', path)
70
- model_read = model_read and model_read.group(1) in MODELS
 
71
  if method in ('GET', 'HEAD'):
72
- if path not in reads and not session_read and not model_read:
73
  return await reject(404, 'Not available in this demo.')
74
- if self.store is not None and path in ('/api/health', '/api/models', '/api/sessions'):
75
  from plastic.api.service import model_summary, sanitize
76
- models = [rec for rec in self.store.list_models() if rec['model_id'] in MODELS]
77
- sessions = [rec for rec in self.store.list_sessions() if rec['session_id'] in SESSIONS]
 
78
  if path == '/api/models':
79
- result = [model_summary(self.store, rec) for rec in models]
80
  elif path == '/api/sessions':
81
- result = sessions
82
  else:
83
  result = {'ok': True, 'artifacts_root': self.store.root, 'device': self.device,
84
- 'n_models': len(models), 'n_sessions': len(sessions),
85
- 'capabilities': dict(PUBLIC_CAPABILITIES), 'public': True}
86
  return await JSONResponse(sanitize(result))(scope, receive, send)
87
  return await self.app(scope, receive, send)
88
- action_match = re.fullmatch(r'/api/sessions/(demo_text)/(chat|reset|resume)', path)
89
- if method != 'POST' or not action_match:
 
90
  return await reject(403, 'This action is unavailable in the shared demo.')
91
- sid, action = action_match.groups()
92
  raw = bytearray()
93
  while True:
94
  msg = await receive()
@@ -101,13 +194,17 @@ class PublicDemoGate:
101
  break
102
  try:
103
  body = json.loads(raw or b'{}')
104
- valid = _valid_body(action, body)
105
  except (ValueError, TypeError, OverflowError):
106
  valid = False
107
  if not valid:
 
 
108
  return await reject(422, 'Use a prompt up to 1024 characters, 0–128 output tokens, and valid numeric settings.')
 
 
109
  if self.busy.locked():
110
- return await reject(503, 'Another visitor is running the shared CPU demo. Retry shortly.')
111
  async with self.busy:
112
  if self.store is not None and action == 'chat':
113
  meta = self.store.load_session_meta(sid)
 
12
  from fastapi.staticfiles import StaticFiles
13
  from deploy.huggingface.pretrained import MODEL_ID
14
 
 
 
15
  MAX_BODY = 8192
16
+ DEMO_SESSION = 'demo_text'
17
+
18
+ # Hosted sleep is bounded: cheap methods, the fast-weight target, a few steps, a few probes. The GPU is
19
+ # shared with chat, so one run at a time. Everything else uses the server's defaults.
20
+ SLEEP_LIMITS = {'methods': ('anchor', 'replay'), 'target': 'w0', 'steps': 10, 'seq_len': 256, 'batch_size': 1,
21
+ 'replay_rows': 8, 'heldout_rows': 2, 'probes': 6, 'probe_chars': 300}
22
+ SLEEP_KEYS = {'method', 'target', 'steps', 'seq_len', 'batch_size', 'replay_rows', 'heldout_rows', 'anchor_lambda', 'sessions', 'probes'}
23
 
24
 
25
  def _integer(value, low, high):
 
48
  return False
49
 
50
 
51
+ def _valid_sleep_body(body, public_sessions):
52
+ L = SLEEP_LIMITS
53
+ if not isinstance(body, dict) or not set(body) <= SLEEP_KEYS:
54
+ return False
55
+ if body.get('method', 'anchor') not in L['methods'] or body.get('target', 'w0') != L['target']:
56
+ return False
57
+ if not (_integer(body.get('steps', 1), 1, L['steps']) and _integer(body.get('seq_len', 256), 32, L['seq_len'])
58
+ and _integer(body.get('batch_size', 1), 1, L['batch_size']) and _integer(body.get('replay_rows', 8), 0, L['replay_rows'])
59
+ and _integer(body.get('heldout_rows', 2), 0, L['heldout_rows']) and _number(body.get('anchor_lambda', 0.5), 0, 1)):
60
+ return False
61
+ sessions = body.get('sessions')
62
+ if sessions is not None and not (isinstance(sessions, list) and sessions and set(sessions) <= set(public_sessions)):
63
+ return False
64
+ probes = body.get('probes')
65
+ if probes is not None:
66
+ if not (isinstance(probes, list) and 1 <= len(probes) <= L['probes']):
67
+ return False
68
+ for p in probes:
69
+ if not (isinstance(p, dict) and set(p) <= {'question', 'answer', 'paraphrase'}
70
+ and isinstance(p.get('question'), str) and 0 < len(p['question']) <= L['probe_chars']
71
+ and isinstance(p.get('answer'), str) and 0 < len(p['answer']) <= 100
72
+ and (p.get('paraphrase') is None or (isinstance(p['paraphrase'], str) and len(p['paraphrase']) <= L['probe_chars']))):
73
+ return False
74
+ return True
75
+
76
+
77
+ # what the shared demo lets a visitor do; the UI renders exactly this set. Sleep is on only when the public
78
+ # model has fast weights to consolidate (a TTT record), which is decided from the store at request time.
79
  PUBLIC_CAPABILITIES = {'create_session': False, 'fork': False, 'reset': True, 'delete': False, 'resume': True, 'calibrate': False, 'sleep': False}
80
 
81
 
82
  class PublicDemoGate:
83
+ """Expose the fixed text playground without changing the local research API.
84
+
85
+ The public catalog is the pinned model plus every model sleep derived from it, and one demo session per
86
+ model (``demo_text`` for the root, ``demo_<child>`` for a child, created when the child appears)."""
87
+ def __init__(self, app, store=None, device='cpu', model_id=MODEL_ID):
88
  self.app = app
89
  self.store = store
90
  self.device = device
91
+ self.model_id = model_id
92
  self.busy = asyncio.Lock()
93
 
94
+ # ------------------------------------------------------------------ the public catalog
95
+ def public_models(self):
96
+ if self.store is None:
97
+ return [self.model_id]
98
+ by_parent = {}
99
+ for rec in self.store.list_models():
100
+ by_parent.setdefault(rec.get('parent_model_id'), []).append(rec['model_id'])
101
+ out, queue = [], [self.model_id]
102
+ while queue:
103
+ mid = queue.pop(0)
104
+ if mid in out:
105
+ continue
106
+ out.append(mid)
107
+ queue.extend(sorted(by_parent.get(mid, [])))
108
+ return out
109
+
110
+ def public_sessions(self, models=None):
111
+ models = models or self.public_models()
112
+ if self.store is None:
113
+ return [DEMO_SESSION]
114
+ wanted = {DEMO_SESSION} | {f'demo_{m}' for m in models[1:]}
115
+ return [rec['session_id'] for rec in self.store.list_sessions() if rec['session_id'] in wanted and rec.get('model_id') in models]
116
+
117
+ def sleep_enabled(self):
118
+ if self.store is None:
119
+ return False
120
+ try:
121
+ return self.store.load_model_record(self.model_id).get('backend') == 'ttt'
122
+ except (FileNotFoundError, KeyError):
123
+ return False
124
+
125
+ def capabilities(self):
126
+ return {**PUBLIC_CAPABILITIES, 'sleep': self.sleep_enabled()}
127
+
128
+ def ensure_child_sessions(self):
129
+ """A demo session for every accepted sleep child, so a visitor can ask the child what the parent was taught."""
130
+ if self.store is None:
131
+ return
132
+ from deploy.huggingface.pretrained import NATIVE_HARNESS
133
+ for mid in self.public_models()[1:]:
134
+ sid = f'demo_{mid}'
135
+ if not self.store.session_exists(sid):
136
+ self.store.create_session(sid, model_id=mid, domain='text', harness_cfg=NATIVE_HARNESS)
137
+
138
+ def sleep_running(self):
139
+ jobs = getattr(getattr(self.app, 'state', None), 'sleep_jobs', None)
140
+ return jobs is not None and any(j.get('status') == 'running' for j in jobs.list())
141
+
142
+ # ------------------------------------------------------------------ the gate
143
  async def __call__(self, scope, receive, send):
144
  if scope['type'] != 'http' or not scope['path'].startswith('/api'):
145
  return await self.app(scope, receive, send)
 
148
  async def reject(status, message):
149
  await JSONResponse({'detail': message}, status_code=status)(scope, receive, send)
150
 
151
+ models = self.public_models()
152
+ sleep_on = self.sleep_enabled()
153
+ if sleep_on and path in ('/api/models', '/api/sessions') or path.startswith('/api/sleep'):
154
+ self.ensure_child_sessions()
155
+ sessions = self.public_sessions(models)
156
  reads = ('/api/health', '/api/models', '/api/sessions')
157
  session_read = re.fullmatch(r'/api/sessions/([^/]+)(?:/(state|transactions))?', path)
158
+ session_read = session_read and session_read.group(1) in sessions
159
  model_read = re.fullmatch(r'/api/models/([^/]+)', path)
160
+ model_read = model_read and model_read.group(1) in models
161
+ sleep_read = sleep_on and re.fullmatch(r'/api/sleep(?:/[^/]+)?', path)
162
  if method in ('GET', 'HEAD'):
163
+ if path not in reads and not session_read and not model_read and not sleep_read:
164
  return await reject(404, 'Not available in this demo.')
165
+ if self.store is not None and path in reads:
166
  from plastic.api.service import model_summary, sanitize
167
+ by_id = {rec['model_id']: rec for rec in self.store.list_models()}
168
+ recs = [by_id[m] for m in models if m in by_id] # lineage order: the root first, then its children
169
+ sess = [rec for rec in self.store.list_sessions() if rec['session_id'] in sessions]
170
  if path == '/api/models':
171
+ result = [model_summary(self.store, rec) for rec in recs]
172
  elif path == '/api/sessions':
173
+ result = sess
174
  else:
175
  result = {'ok': True, 'artifacts_root': self.store.root, 'device': self.device,
176
+ 'n_models': len(recs), 'n_sessions': len(sess),
177
+ 'capabilities': self.capabilities(), 'public': True}
178
  return await JSONResponse(sanitize(result))(scope, receive, send)
179
  return await self.app(scope, receive, send)
180
+ action_match = re.fullmatch(r'/api/sessions/([^/]+)/(chat|reset|resume)', path)
181
+ sleep_match = sleep_on and re.fullmatch(rf'/api/models/({re.escape(self.model_id)})/sleep', path)
182
+ if method != 'POST' or not (action_match and action_match.group(1) in sessions or sleep_match):
183
  return await reject(403, 'This action is unavailable in the shared demo.')
184
+ sid, action = action_match.groups() if action_match else (None, 'sleep')
185
  raw = bytearray()
186
  while True:
187
  msg = await receive()
 
194
  break
195
  try:
196
  body = json.loads(raw or b'{}')
197
+ valid = _valid_sleep_body(body, sessions) if action == 'sleep' else _valid_body(action, body)
198
  except (ValueError, TypeError, OverflowError):
199
  valid = False
200
  if not valid:
201
+ if action == 'sleep':
202
+ return await reject(422, 'Hosted sleep accepts anchor or replay on W0, up to 10 steps, 256 tokens, batch 1, 8 replay rows, 2 held-out rows and 6 probes, over the public sessions.')
203
  return await reject(422, 'Use a prompt up to 1024 characters, 0–128 output tokens, and valid numeric settings.')
204
+ if action == 'sleep' and self.sleep_running():
205
+ return await reject(409, 'A sleep run is already in progress. Wait for its card to finish.')
206
  if self.busy.locked():
207
+ return await reject(503, 'Another visitor is using the shared demo. Retry shortly.')
208
  async with self.busy:
209
  if self.store is not None and action == 'chat':
210
  meta = self.store.load_session_meta(sid)
deploy/huggingface/pretrained.py CHANGED
@@ -20,6 +20,12 @@ def download_checkpoint(target: Path) -> None:
20
  allow_patterns=['*.json', '*.safetensors', '*.jinja', 'LICENSE', 'README.md'])
21
 
22
 
 
 
 
 
 
 
23
  def prepare_pretrained_sessions(store: ArtifactStore, checkpoint: Path) -> None:
24
  from plastic.backends.qwen import _checkpoint_digest
25
  if _checkpoint_digest(str(checkpoint)) != CHECKPOINT_DIGEST:
@@ -35,10 +41,7 @@ def prepare_pretrained_sessions(store: ArtifactStore, checkpoint: Path) -> None:
35
  'checkpoint_dir': str(checkpoint.resolve()), 'checkpoint_digest': CHECKPOINT_DIGEST,
36
  'chunk': 8,
37
  })
38
- # Keep normal context processing for both prompt and generated tokens. Signals are visible,
39
- # but the unfinished Qwen retention policy must not freeze or reject ordinary conversation.
40
- native = HarnessConfig(log_only=True, learn_from_generation=True, freeze_on_alarm=False,
41
- enable_projection=False, enable_budget=False)
42
  for sid, mid, domain, harness in [
43
  ('demo_text', MODEL_ID, 'text', native),
44
  ]:
 
20
  allow_patterns=['*.json', '*.safetensors', '*.jinja', 'LICENSE', 'README.md'])
21
 
22
 
23
+ # Keep normal context processing for both prompt and generated tokens. Signals are visible, but the
24
+ # unfinished retention policy must not freeze or reject ordinary conversation.
25
+ NATIVE_HARNESS = HarnessConfig(log_only=True, learn_from_generation=True, freeze_on_alarm=False,
26
+ enable_projection=False, enable_budget=False)
27
+
28
+
29
  def prepare_pretrained_sessions(store: ArtifactStore, checkpoint: Path) -> None:
30
  from plastic.backends.qwen import _checkpoint_digest
31
  if _checkpoint_digest(str(checkpoint)) != CHECKPOINT_DIGEST:
 
41
  'checkpoint_dir': str(checkpoint.resolve()), 'checkpoint_digest': CHECKPOINT_DIGEST,
42
  'chunk': 8,
43
  })
44
+ native = NATIVE_HARNESS
 
 
 
45
  for sid, mid, domain, harness in [
46
  ('demo_text', MODEL_ID, 'text', native),
47
  ]:
deploy/huggingface/test_space.py CHANGED
@@ -1,6 +1,7 @@
1
  """Public hosting boundaries: exercise route, payload, and concurrency families."""
2
  import asyncio
3
  import json
 
4
 
5
  import httpx
6
  import pytest
@@ -218,3 +219,89 @@ def test_pretrained_demo_refuses_incompatible_artifacts_or_sessions(tmp_path, mo
218
  assert store.load_session_meta('demo_text') == before
219
  else:
220
  assert not store.list_sessions()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """Public hosting boundaries: exercise route, payload, and concurrency families."""
2
  import asyncio
3
  import json
4
+ import time
5
 
6
  import httpx
7
  import pytest
 
219
  assert store.load_session_meta('demo_text') == before
220
  else:
221
  assert not store.list_sessions()
222
+
223
+
224
+ def _ttt_public_store(tmp_path):
225
+ """A store whose public model is a TTT record with one sleep child already present."""
226
+ from plastic.harness.config import HarnessConfig
227
+ from plastic.store import ArtifactStore
228
+ store = ArtifactStore(str(tmp_path / 'store'))
229
+ ckpt = tmp_path / 'ckpt'
230
+ ckpt.mkdir(exist_ok=True)
231
+ store.register_model('ttt_pub', {'backend': 'ttt', 'domain': 'text', 'status': 'completed', 'params': 10, 'checkpoint_dir': str(ckpt)})
232
+ store.register_model('sleep_a', {'backend': 'ttt', 'domain': 'text', 'status': 'completed', 'params': 10, 'checkpoint_dir': str(ckpt),
233
+ 'parent_model_id': 'ttt_pub', 'type': 'sleep'})
234
+ store.register_model('unrelated', {'backend': 'ttt', 'domain': 'text', 'status': 'completed', 'params': 10, 'checkpoint_dir': str(ckpt)})
235
+ store.create_session('demo_text', model_id='ttt_pub', domain='text', harness_cfg=HarnessConfig())
236
+ store.create_session('private', model_id='ttt_pub', domain='text', harness_cfg=HarnessConfig())
237
+ return store
238
+
239
+
240
+ def test_public_sleep_is_closed_while_the_public_model_has_no_fast_weights():
241
+ with TestClient(fake_app()) as client:
242
+ assert client.get('/api/sleep').status_code == 404
243
+ assert client.post(f'/api/models/{MODEL_ID}/sleep', json={}).status_code == 403
244
+
245
+
246
+ def test_public_catalog_follows_sleep_lineage_and_opens_bounded_sleep_for_a_ttt_model(tmp_path, monkeypatch):
247
+ import sys
248
+ from plastic.api import sleep_jobs
249
+ from plastic.api.app import create_app
250
+ store = _ttt_public_store(tmp_path)
251
+ app = create_app(str(tmp_path / 'store'), device='cpu')
252
+
253
+ def fake_argv(model_id, run_dir, artifacts_root, device, options, sessions, probes_path):
254
+ script = ("import json,sys,os; d=sys.argv[1]; open(os.path.join(d,'log.txt'),'a').write('[sleep] stand-in\\n');"
255
+ f"json.dump({{'run_id': os.path.basename(d), 'parent_model_id': {model_id!r}, 'status': 'accepted', 'model_id': 'sleep_b',"
256
+ " 'gate': {'passed': True, 'measured': True, 'checks': []}}, open(os.path.join(d,'sleep_report.json'),'w'));"
257
+ "import shutil")
258
+ return [sys.executable, '-c', script, run_dir]
259
+
260
+ monkeypatch.setattr(sleep_jobs, 'build_sleep_argv', fake_argv)
261
+ with TestClient(PublicDemoGate(app, store, 'cpu', model_id='ttt_pub')) as client:
262
+ health = client.get('/api/health').json()
263
+ assert health['capabilities']['sleep'] is True and health['n_models'] == 2
264
+ # the catalog: the public model and its descendant, never the unrelated record or the private session
265
+ assert [m['model_id'] for m in client.get('/api/models').json()] == ['ttt_pub', 'sleep_a']
266
+ assert client.get('/api/models/unrelated').status_code == 404
267
+ assert client.get('/api/models/sleep_a').status_code == 200
268
+ # the child got a demo session on first sight; the private session stays private
269
+ assert [s['session_id'] for s in client.get('/api/sessions').json()] == ['demo_sleep_a', 'demo_text'] or \
270
+ sorted(s['session_id'] for s in client.get('/api/sessions').json()) == ['demo_sleep_a', 'demo_text']
271
+ assert client.get('/api/sessions/private').status_code == 404
272
+ assert client.post('/api/sessions/demo_sleep_a/reset', json={}).status_code == 200
273
+ assert client.get('/api/sleep').status_code == 200
274
+ # bounded body family
275
+ for bad in ({'method': 'distill'}, {'target': 'all'}, {'steps': 11}, {'seq_len': 512}, {'batch_size': 2}, {'lr': 1e-3},
276
+ {'sessions': ['private']}, {'sessions': []}, {'probes': [{'question': 'q', 'answer': 'x' * 101}]},
277
+ {'probes': [{'question': 'q', 'answer': 'a'}] * 7}):
278
+ assert client.post('/api/models/ttt_pub/sleep', json=bad).status_code == 422, bad
279
+ assert client.post('/api/models/sleep_a/sleep', json={}).status_code == 403 # only the root model sleeps publicly
280
+ r = client.post('/api/models/ttt_pub/sleep', json={'method': 'anchor', 'sessions': ['demo_text'],
281
+ 'probes': [{'question': 'q', 'answer': 'a', 'paraphrase': 'q2'}]})
282
+ assert r.status_code == 200, r.text
283
+ run_id = r.json()['run_id']
284
+ for _ in range(100):
285
+ s = client.get(f'/api/sleep/{run_id}').json()
286
+ if s['status'] != 'running':
287
+ break
288
+ time.sleep(0.05)
289
+ assert s['status'] == 'accepted' and s['report']['model_id'] == 'sleep_b'
290
+ # the new child needs a record for the catalog to pick it up (the real run registers it; the stand-in did not)
291
+ store.register_model('sleep_b', {'backend': 'ttt', 'domain': 'text', 'status': 'completed', 'params': 10,
292
+ 'checkpoint_dir': str(tmp_path / 'ckpt'), 'parent_model_id': 'ttt_pub', 'type': 'sleep'})
293
+ assert [m['model_id'] for m in client.get('/api/models').json()] == ['ttt_pub', 'sleep_a', 'sleep_b']
294
+ assert 'demo_sleep_b' in [x['session_id'] for x in client.get('/api/sessions').json()]
295
+ assert client.get('/api/sessions/demo_sleep_b/state').status_code == 200
296
+
297
+
298
+ def test_public_sleep_refuses_a_second_concurrent_run(tmp_path, monkeypatch):
299
+ import sys
300
+ from plastic.api import sleep_jobs
301
+ from plastic.api.app import create_app
302
+ store = _ttt_public_store(tmp_path)
303
+ app = create_app(str(tmp_path / 'store'), device='cpu')
304
+ monkeypatch.setattr(sleep_jobs, 'build_sleep_argv', lambda *a, **k: [sys.executable, '-c', 'import time; time.sleep(2)'])
305
+ with TestClient(PublicDemoGate(app, store, 'cpu', model_id='ttt_pub')) as client:
306
+ assert client.post('/api/models/ttt_pub/sleep', json={'method': 'anchor'}).status_code == 200
307
+ assert client.post('/api/models/ttt_pub/sleep', json={'method': 'anchor'}).status_code == 409
source_snapshot.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "github_repository": "DMontgomery40/plastic",
3
- "github_commit": "46d0a06830a01315a1b201feca14ca2f47217768",
4
- "preserved_hf_revision": "06bafd8484fb3b678e2f8d9a46b539ec8015feab",
5
  "repo_type": "space"
6
  }
 
1
  {
2
  "github_repository": "DMontgomery40/plastic",
3
+ "github_commit": "db71f96317a1a1dc848e887c03cf5eaefb27cc84",
4
+ "preserved_hf_revision": "ee600ac43cdc19462ab2057cc3290187a7524b41",
5
  "repo_type": "space"
6
  }