vimalk78 commited on
Commit
c09e7f4
Β·
verified Β·
1 Parent(s): 555af9e

feat: structural probes tab + galaxy ns fix

Browse files
Files changed (2) hide show
  1. __pycache__/app.cpython-314.pyc +0 -0
  2. app.py +746 -15
__pycache__/app.cpython-314.pyc CHANGED
Binary files a/__pycache__/app.cpython-314.pyc and b/__pycache__/app.cpython-314.pyc differ
 
app.py CHANGED
@@ -254,6 +254,17 @@ def _build_galaxy_figure(data_path: str):
254
  for k in top_kinds:
255
  series.append((k, color_map[k], [i for i, kk in enumerate(kinds) if kk == k]))
256
 
 
 
 
 
 
 
 
 
 
 
 
257
  for label, color, idxs in series:
258
  if not idxs:
259
  continue
@@ -263,9 +274,7 @@ def _build_galaxy_figure(data_path: str):
263
  mode="markers",
264
  name=f"{label} ({len(idxs):,})",
265
  marker=dict(size=4, color=color, opacity=0.65),
266
- text=[(f"<b>{kinds[i]}</b><br>"
267
- f"{data['name'][i]}<br>"
268
- f"ns: {data['namespace'][i]}") for i in idxs],
269
  hovertemplate="%{text}<extra></extra>",
270
  )
271
 
@@ -291,6 +300,567 @@ except FileNotFoundError:
291
  _log(f"Galaxy data not found at {GALAXY_DATA_PATH} β€” galaxy tab will be empty")
292
 
293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
  # ----- UI -----
295
 
296
  EXAMPLE_NGINX = """apiVersion: apps/v1
@@ -558,6 +1128,11 @@ roleRef:
558
  """
559
 
560
  _log("Building Gradio UI...")
 
 
 
 
 
561
  with gr.Blocks(title="YAML-BERT") as demo:
562
  gr.Markdown(
563
  f"""
@@ -567,7 +1142,7 @@ Code: [github.com/vimalk78/yaml-bert](https://github.com/vimalk78/yaml-bert) Β·
567
  Trained with MLM + reconstruction on 276K K8s manifests Β·
568
  {n_params:,} params
569
 
570
- **This Space includes 2 demos β€” pick a tab below, or use the tiles on the Overview tab.**
571
  """
572
  )
573
 
@@ -575,28 +1150,37 @@ Trained with MLM + reconstruction on 276K K8s manifests Β·
575
  with gr.Tab("Overview", id="overview"):
576
  gr.Markdown("### Demos in this Space")
577
  with gr.Row():
578
- with gr.Column():
579
  gr.Markdown(
580
  "#### 🧩 Missing-field suggester\n"
581
- "Paste a Kubernetes YAML manifest. The model walks each "
582
- "parent level, identifies fields it expects to see there "
583
- "but that are absent, and ranks the suggestions by "
584
- "confidence."
585
  )
586
  open_suggester = gr.Button(
587
  "Open missing-field suggester β†’", variant="primary"
588
  )
589
- with gr.Column():
590
  gr.Markdown(
591
  "#### 🌌 Manifest galaxy\n"
592
- "10,000 Kubernetes manifests embedded by the model and "
593
- "projected to 2D. Watch clusters of `Deployment`, "
594
- "`Service`, `ConfigMap` etc. form spontaneously β€” the "
595
- "model was never told what `kind` is."
596
  )
597
  open_galaxy = gr.Button(
598
  "Open manifest galaxy β†’", variant="primary"
599
  )
 
 
 
 
 
 
 
 
 
 
 
600
 
601
  with gr.Tab("Missing-field suggester", id="suggester"):
602
  gr.Markdown(
@@ -684,11 +1268,158 @@ Trained with MLM + reconstruction on 276K K8s manifests Β·
684
  "Click a legend entry to toggle that kind on/off."
685
  )
686
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
687
  open_suggester.click(lambda: gr.Tabs(selected="suggester"), outputs=tabs)
688
  open_galaxy.click(lambda: gr.Tabs(selected="galaxy"), outputs=tabs)
 
689
 
690
 
691
  _log("Gradio UI built β€” launching")
692
 
693
  if __name__ == "__main__":
694
- demo.launch()
 
254
  for k in top_kinds:
255
  series.append((k, color_map[k], [i for i, kk in enumerate(kinds) if kk == k]))
256
 
257
+ def _hover(i: int) -> str:
258
+ parts = [f"<b>{kinds[i]}</b>", data["name"][i]]
259
+ ns = data["namespace"][i]
260
+ # "(default)" is the build-time placeholder when the manifest didn't
261
+ # specify a namespace β€” true for all cluster-scoped kinds (Namespace,
262
+ # ClusterRole, CRD, …) and for namespaced resources that omit it.
263
+ # Showing "ns: (default)" for these is misleading, so suppress.
264
+ if ns and ns != "(default)":
265
+ parts.append(f"ns: {ns}")
266
+ return "<br>".join(parts)
267
+
268
  for label, color, idxs in series:
269
  if not idxs:
270
  continue
 
274
  mode="markers",
275
  name=f"{label} ({len(idxs):,})",
276
  marker=dict(size=4, color=color, opacity=0.65),
277
+ text=[_hover(i) for i in idxs],
 
 
278
  hovertemplate="%{text}<extra></extra>",
279
  )
280
 
 
300
  _log(f"Galaxy data not found at {GALAXY_DATA_PATH} β€” galaxy tab will be empty")
301
 
302
 
303
+ # ----- Structural probes -----
304
+ #
305
+ # Presets of hand-crafted manifests that probe whether the model encodes
306
+ # specific structural distinctions. Each preset's manifests are encoded to
307
+ # doc_vecs, projected to 2D via MDS (preserves pairwise cosine distances),
308
+ # and shown as a scatter plot. Users can add their own YAMLs to see where
309
+ # they land relative to the preset.
310
+
311
+ # ---- Preset manifests ----
312
+
313
+ _POD_NGINX = """apiVersion: v1
314
+ kind: Pod
315
+ metadata:
316
+ name: nginx-app
317
+ spec:
318
+ containers:
319
+ - name: app
320
+ image: nginx
321
+ ports:
322
+ - containerPort: 80
323
+ """
324
+
325
+ _POD_REDIS = """apiVersion: v1
326
+ kind: Pod
327
+ metadata:
328
+ name: redis-app
329
+ spec:
330
+ containers:
331
+ - name: app
332
+ image: redis
333
+ ports:
334
+ - containerPort: 6379
335
+ """
336
+
337
+ _POD_NGINX_INIT = """apiVersion: v1
338
+ kind: Pod
339
+ metadata:
340
+ name: nginx-with-init
341
+ spec:
342
+ initContainers:
343
+ - name: setup
344
+ image: busybox
345
+ command: ["sh", "-c", "echo init"]
346
+ containers:
347
+ - name: app
348
+ image: nginx
349
+ ports:
350
+ - containerPort: 80
351
+ """
352
+
353
+ _POD_REDIS_INIT = """apiVersion: v1
354
+ kind: Pod
355
+ metadata:
356
+ name: redis-with-init
357
+ spec:
358
+ initContainers:
359
+ - name: setup
360
+ image: busybox
361
+ command: ["sh", "-c", "echo init"]
362
+ containers:
363
+ - name: app
364
+ image: redis
365
+ ports:
366
+ - containerPort: 6379
367
+ """
368
+
369
+ _SVC_CLUSTERIP_WEB = """apiVersion: v1
370
+ kind: Service
371
+ metadata:
372
+ name: web-clusterip
373
+ spec:
374
+ type: ClusterIP
375
+ selector:
376
+ app: web
377
+ ports:
378
+ - port: 80
379
+ targetPort: 8080
380
+ """
381
+
382
+ _SVC_CLUSTERIP_API = """apiVersion: v1
383
+ kind: Service
384
+ metadata:
385
+ name: api-clusterip
386
+ spec:
387
+ type: ClusterIP
388
+ selector:
389
+ app: api
390
+ ports:
391
+ - port: 443
392
+ targetPort: 8443
393
+ """
394
+
395
+ _SVC_NODEPORT = """apiVersion: v1
396
+ kind: Service
397
+ metadata:
398
+ name: web-nodeport
399
+ spec:
400
+ type: NodePort
401
+ selector:
402
+ app: web
403
+ ports:
404
+ - port: 80
405
+ targetPort: 8080
406
+ nodePort: 30080
407
+ """
408
+
409
+ _SVC_LOADBALANCER = """apiVersion: v1
410
+ kind: Service
411
+ metadata:
412
+ name: web-lb
413
+ spec:
414
+ type: LoadBalancer
415
+ selector:
416
+ app: web
417
+ externalTrafficPolicy: Local
418
+ ports:
419
+ - port: 80
420
+ targetPort: 8080
421
+ """
422
+
423
+ _DEPLOY_NGINX = """apiVersion: apps/v1
424
+ kind: Deployment
425
+ metadata:
426
+ name: nginx
427
+ spec:
428
+ replicas: 3
429
+ selector:
430
+ matchLabels:
431
+ app: nginx
432
+ template:
433
+ metadata:
434
+ labels:
435
+ app: nginx
436
+ spec:
437
+ containers:
438
+ - name: app
439
+ image: nginx
440
+ ports:
441
+ - containerPort: 80
442
+ """
443
+
444
+ _CONFIGMAP_APP = """apiVersion: v1
445
+ kind: ConfigMap
446
+ metadata:
447
+ name: app-config
448
+ data:
449
+ config.yaml: |
450
+ debug: true
451
+ app.properties: |
452
+ key1=value1
453
+ """
454
+
455
+ _POD_NS_PROD_1 = """apiVersion: v1
456
+ kind: Pod
457
+ metadata:
458
+ name: web-1
459
+ namespace: production
460
+ spec:
461
+ containers:
462
+ - name: app
463
+ image: nginx
464
+ ports:
465
+ - containerPort: 80
466
+ """
467
+
468
+ _POD_NS_PROD_2 = """apiVersion: v1
469
+ kind: Pod
470
+ metadata:
471
+ name: web-2
472
+ namespace: production
473
+ spec:
474
+ containers:
475
+ - name: app
476
+ image: nginx
477
+ ports:
478
+ - containerPort: 80
479
+ """
480
+
481
+ _POD_NS_STAGING_1 = """apiVersion: v1
482
+ kind: Pod
483
+ metadata:
484
+ name: web-1
485
+ namespace: staging
486
+ spec:
487
+ containers:
488
+ - name: app
489
+ image: nginx
490
+ ports:
491
+ - containerPort: 80
492
+ """
493
+
494
+ _POD_NS_STAGING_2 = """apiVersion: v1
495
+ kind: Pod
496
+ metadata:
497
+ name: web-2
498
+ namespace: staging
499
+ spec:
500
+ containers:
501
+ - name: app
502
+ image: nginx
503
+ ports:
504
+ - containerPort: 80
505
+ """
506
+
507
+
508
+ def _verdict_init(cos):
509
+ cd = float(cos[2][3])
510
+ mx = float(max(cos[0][2], cos[1][3]))
511
+ passed = cd > mx
512
+ msg = (
513
+ f"`cos(C, D)` = **{cd:.3f}** (both have init) Β· "
514
+ f"`max(cos(A,C), cos(B,D))` = **{mx:.3f}** (mixed). "
515
+ + ("Init-pairs cluster tighter than mixed pairs β€” the model treats "
516
+ "`initContainers` as a real structural feature."
517
+ if passed else
518
+ "Mixed pairs are at least as close as init-pairs β€” the model "
519
+ "does not cleanly separate Pods by `initContainers` presence here.")
520
+ )
521
+ return passed, msg
522
+
523
+
524
+ def _verdict_service_type(cos):
525
+ same = float(cos[0][1])
526
+ cross = float(max(cos[0][2], cos[0][3], cos[1][2], cos[1][3], cos[2][3]))
527
+ passed = same > cross
528
+ msg = (
529
+ f"`cos(A, B)` = **{same:.3f}** (both ClusterIP) Β· "
530
+ f"`max(cross-type)` = **{cross:.3f}**. "
531
+ + ("Same-type pairs cluster tighter than cross-type pairs β€” the "
532
+ "model has internalized the `type` distinction (likely through "
533
+ "the structural keys each type adds: `nodePort`, "
534
+ "`externalTrafficPolicy`)."
535
+ if passed else
536
+ "Same-type pairs do not cluster more tightly than cross-type "
537
+ "pairs β€” `type` is not a primary axis in the embedding here.")
538
+ )
539
+ return passed, msg
540
+
541
+
542
+ def _verdict_namespace(cos):
543
+ # A, B in production Β· C, D in staging β€” all otherwise identical Pods.
544
+ same_ns = float(min(cos[0][1], cos[2][3]))
545
+ cross_ns = float(max(cos[0][2], cos[0][3], cos[1][2], cos[1][3]))
546
+ passed = same_ns > cross_ns
547
+ msg = (
548
+ f"`min(same-ns cos)` = **{same_ns:.3f}** Β· "
549
+ f"`max(cross-ns cos)` = **{cross_ns:.3f}**. "
550
+ + ("Same-namespace pairs cluster tighter β€” the model has somehow "
551
+ "encoded namespace as a feature (surprising, since namespace is "
552
+ "a leaf VALUE per the design rationale)."
553
+ if passed else
554
+ "Same-namespace and cross-namespace pairs have indistinguishable "
555
+ "cosines β€” the model is value-blind for namespace. This matches "
556
+ "the design: values are second-class in `doc_vec`. Compare with "
557
+ "the Service-type probe (passes) β€” `type` values matter because "
558
+ "they bring structural KEYS along, while namespace values don't.")
559
+ )
560
+ return passed, msg
561
+
562
+
563
+ def _verdict_cross_kind(cos):
564
+ # A=Pod nginx, B=Pod redis, C=Deployment wrapping nginx, D=ConfigMap
565
+ pod_pod = float(cos[0][1]) # both Pods
566
+ pod_deploy = float(cos[0][2]) # Pod ↔ Deployment-wrapping-that-Pod
567
+ pod_cm = float(cos[0][3]) # Pod ↔ unrelated kind
568
+ deploy_cm = float(cos[2][3]) # Deployment ↔ unrelated kind
569
+ passed = pod_deploy > max(pod_cm, deploy_cm)
570
+ msg = (
571
+ f"`cos(Pod, Deployment-wrapping-it)` = **{pod_deploy:.3f}** Β· "
572
+ f"`cos(Pod, ConfigMap)` = **{pod_cm:.3f}** Β· "
573
+ f"`cos(Pod, Pod)` = **{pod_pod:.3f}** (kind silo). "
574
+ + ("Pod and the Deployment that wraps it are closer than either is "
575
+ "to an unrelated ConfigMap β€” the model sees them as a family."
576
+ if passed else
577
+ "Pod-Deployment family is not detected β€” kinds form sharp silos "
578
+ "in the embedding.")
579
+ )
580
+ return passed, msg
581
+
582
+
583
+ PRESETS = [
584
+ {
585
+ "id": "init",
586
+ "title": "Pod Β± initContainers",
587
+ "hypothesis": (
588
+ "If `initContainers` is a meaningful structural feature, two "
589
+ "Pods that both have one should be closer in embedding space "
590
+ "than a Pod with one and a structurally similar Pod without."
591
+ ),
592
+ "manifests": [
593
+ {"name": "nginx (no init)", "yaml": _POD_NGINX},
594
+ {"name": "redis (no init)", "yaml": _POD_REDIS},
595
+ {"name": "nginx + init", "yaml": _POD_NGINX_INIT},
596
+ {"name": "redis + init", "yaml": _POD_REDIS_INIT},
597
+ ],
598
+ "verdict_fn": _verdict_init,
599
+ },
600
+ {
601
+ "id": "service-type",
602
+ "title": "Service type (ClusterIP / NodePort / LoadBalancer)",
603
+ "hypothesis": (
604
+ "Each Service `type` brings its own structural keys "
605
+ "(`nodePort`, `externalTrafficPolicy`, …). Same-type Services "
606
+ "should cluster, even with different selectors/ports."
607
+ ),
608
+ "manifests": [
609
+ {"name": "ClusterIP β€” app=web", "yaml": _SVC_CLUSTERIP_WEB},
610
+ {"name": "ClusterIP β€” app=api", "yaml": _SVC_CLUSTERIP_API},
611
+ {"name": "NodePort β€” app=web", "yaml": _SVC_NODEPORT},
612
+ {"name": "LoadBalancer β€” app=web", "yaml": _SVC_LOADBALANCER},
613
+ ],
614
+ "verdict_fn": _verdict_service_type,
615
+ },
616
+ {
617
+ "id": "namespace",
618
+ "title": "Pods in same namespace vs different namespace",
619
+ "hypothesis": (
620
+ "If the model encodes `metadata.namespace` as a feature, two "
621
+ "Pods in the same namespace should be closer than two Pods in "
622
+ "different namespaces (controlling for structure). "
623
+ "_Honest prediction: this should **fail** β€” namespace is a "
624
+ "leaf value, and values are second-class in `doc_vec`. The "
625
+ "failure would confirm the design rationale; a pass would "
626
+ "refute it._"
627
+ ),
628
+ "manifests": [
629
+ {"name": "production / web-1", "yaml": _POD_NS_PROD_1},
630
+ {"name": "production / web-2", "yaml": _POD_NS_PROD_2},
631
+ {"name": "staging / web-1", "yaml": _POD_NS_STAGING_1},
632
+ {"name": "staging / web-2", "yaml": _POD_NS_STAGING_2},
633
+ ],
634
+ "verdict_fn": _verdict_namespace,
635
+ },
636
+ {
637
+ "id": "cross-kind",
638
+ "title": "Pod vs Deployment wrapping the same Pod",
639
+ "hypothesis": (
640
+ "A Deployment wraps a Pod template inside `spec.template`. "
641
+ "If the model sees them as a related family, the Pod and "
642
+ "Deployment should be closer than either is to an unrelated "
643
+ "kind like ConfigMap."
644
+ ),
645
+ "manifests": [
646
+ {"name": "Pod (nginx)", "yaml": _POD_NGINX},
647
+ {"name": "Pod (redis)", "yaml": _POD_REDIS},
648
+ {"name": "Deployment wrapping nginx", "yaml": _DEPLOY_NGINX},
649
+ {"name": "ConfigMap (unrelated)", "yaml": _CONFIGMAP_APP},
650
+ ],
651
+ "verdict_fn": _verdict_cross_kind,
652
+ },
653
+ ]
654
+
655
+ # Letters & colors used for both plot points and accordion headers.
656
+ _PRESET_PALETTE = [
657
+ "#1f77b4", # A blue
658
+ "#ff7f0e", # B orange
659
+ "#2ca02c", # C green
660
+ "#d62728", # D red
661
+ "#9467bd", # E purple
662
+ "#8c564b", # F brown
663
+ "#e377c2", # G pink
664
+ "#17becf", # H cyan
665
+ ]
666
+ _PRESET_LETTERS = ["A", "B", "C", "D", "E", "F", "G", "H"]
667
+
668
+
669
+ # Reuse one linearizer/annotator/config across calls (cheap, but skip the
670
+ # per-call construction inside _encode_doc_vec).
671
+ def _make_encoder_state():
672
+ from yaml_bert.annotator import DomainAnnotator
673
+ from yaml_bert.config import YamlBertConfig
674
+ from yaml_bert.linearizer import YamlLinearizer
675
+ return YamlLinearizer(), DomainAnnotator(), YamlBertConfig(
676
+ mask_prob=0.0, recon_enabled=False,
677
+ )
678
+
679
+
680
+ _LINEARIZER, _ANNOTATOR, _INFER_CONFIG = _make_encoder_state()
681
+
682
+
683
+ def _encode_doc_vec(yaml_text: str) -> torch.Tensor:
684
+ """Encode one YAML doc and return its doc_vec (shape (d_model,))."""
685
+ from yaml_bert.dataset import YamlBertDataset, collate_fn as _collate
686
+ nodes = _LINEARIZER.linearize(yaml_text)
687
+ if not nodes:
688
+ raise ValueError("YAML produced no nodes")
689
+ _ANNOTATOR.annotate(nodes)
690
+ ds = YamlBertDataset([nodes], VOCAB, _INFER_CONFIG)
691
+ item = ds[0]
692
+ batch = _collate([item])
693
+ with torch.no_grad():
694
+ out = MODEL(
695
+ token_ids=batch["token_ids"],
696
+ node_types=batch["node_types"],
697
+ depths=batch["depths"],
698
+ sibling_indices=batch["sibling_indices"],
699
+ batch_info=batch["batch_info"],
700
+ padding_mask=batch["padding_mask"],
701
+ parent_of_tensor=batch["parent_of_tensor"],
702
+ top_level_key_mask=batch["top_level_key_mask"],
703
+ edges_by_depth=batch["edges_by_depth"],
704
+ parents_by_depth=batch["parents_by_depth"],
705
+ )
706
+ return out[1][0] # (d_model,)
707
+
708
+
709
+ def _layout_2d(vecs):
710
+ """Project doc_vecs to 2D coords via MDS on cosine distances."""
711
+ import numpy as np
712
+ n = len(vecs)
713
+ if n == 1:
714
+ return np.array([[0.0, 0.0]])
715
+ if n == 2:
716
+ return np.array([[-1.0, 0.0], [1.0, 0.0]])
717
+
718
+ if isinstance(vecs, list):
719
+ vecs = torch.stack(vecs)
720
+ vecs_norm = vecs / vecs.norm(dim=1, keepdim=True)
721
+ cos = (vecs_norm @ vecs_norm.t()).numpy()
722
+ dist = 1.0 - cos
723
+ np.fill_diagonal(dist, 0.0)
724
+ dist = np.clip(dist, 0.0, None)
725
+
726
+ from sklearn.manifold import MDS
727
+ mds = MDS(
728
+ n_components=2,
729
+ metric="precomputed",
730
+ random_state=42,
731
+ normalized_stress="auto",
732
+ init="classical_mds",
733
+ )
734
+ return mds.fit_transform(dist)
735
+
736
+
737
+ def _find_identical_groups(items, threshold: float = 0.9999):
738
+ """Find groups of items whose pairwise cosine similarity is ~1.0.
739
+ These represent inputs the model encodes to the same `doc_vec`
740
+ (e.g. when their differing values all map to the same vocab token,
741
+ typically [UNK]). The plot must show this honestly: they overlap.
742
+ """
743
+ if len(items) < 2:
744
+ return []
745
+ vecs = torch.stack([it["vec"] for it in items])
746
+ vecs_norm = vecs / vecs.norm(dim=1, keepdim=True)
747
+ cos = (vecs_norm @ vecs_norm.t()).numpy()
748
+
749
+ groups: list[list[int]] = []
750
+ assigned = [False] * len(items)
751
+ for i in range(len(items)):
752
+ if assigned[i]:
753
+ continue
754
+ group = [i]
755
+ assigned[i] = True
756
+ for j in range(i + 1, len(items)):
757
+ if not assigned[j] and cos[i][j] >= threshold:
758
+ group.append(j)
759
+ assigned[j] = True
760
+ if len(group) > 1:
761
+ groups.append(group)
762
+ return groups
763
+
764
+
765
+ def _collision_note(items):
766
+ """Markdown note when two or more items produce identical doc_vecs."""
767
+ groups = _find_identical_groups(items)
768
+ if not groups:
769
+ return ""
770
+ lines = []
771
+ for g in groups:
772
+ labels = ", ".join(f"`{items[i]['letter']}`" for i in g)
773
+ lines.append(
774
+ f"- {labels} encode to **identical** `doc_vec`s "
775
+ f"(`cos β‰ˆ 1.0`). The plot will show them overlapping β€” that "
776
+ f"is honest: the model cannot tell these inputs apart. "
777
+ f"Likely cause: differing values all collapse to the same "
778
+ f"vocab token (often `[UNK]` when names aren't frequent "
779
+ f"enough in the training corpus to earn a vocab slot)."
780
+ )
781
+ return "\n\n**Identical embeddings detected:**\n" + "\n".join(lines)
782
+
783
+
784
+ def _build_preset_figure(items, hypothesis=""):
785
+ """Build a Plotly scatter from a list of {letter, name, vec, ...} items."""
786
+ import plotly.graph_objects as go
787
+ if not items:
788
+ return go.Figure()
789
+ vecs = [it["vec"] for it in items]
790
+ coords = _layout_2d(vecs)
791
+ colors = [_PRESET_PALETTE[i % len(_PRESET_PALETTE)] for i in range(len(items))]
792
+ letters = [it["letter"] for it in items]
793
+ names = [it["name"] for it in items]
794
+
795
+ fig = go.Figure()
796
+ fig.add_scatter(
797
+ x=coords[:, 0],
798
+ y=coords[:, 1],
799
+ mode="markers+text",
800
+ text=letters,
801
+ textposition="top center",
802
+ textfont=dict(size=14, color="#222"),
803
+ marker=dict(size=18, color=colors, opacity=0.85,
804
+ line=dict(width=2, color="#222")),
805
+ hovertext=[f"<b>{l}</b> β€” {n}" for l, n in zip(letters, names)],
806
+ hovertemplate="%{hovertext}<extra></extra>",
807
+ showlegend=False,
808
+ )
809
+ fig.update_layout(
810
+ title="2D layout (MDS of cosine distances) β€” closer = more similar",
811
+ height=460,
812
+ margin=dict(l=10, r=10, t=50, b=10),
813
+ xaxis=dict(visible=False),
814
+ yaxis=dict(visible=False, scaleanchor="x"),
815
+ plot_bgcolor="white",
816
+ )
817
+ return fig
818
+
819
+
820
+ def _encode_preset(preset):
821
+ """Encode all manifests in a preset; return list of items with vecs."""
822
+ items = []
823
+ for i, m in enumerate(preset["manifests"]):
824
+ vec = _encode_doc_vec(m["yaml"])
825
+ items.append({
826
+ "letter": _PRESET_LETTERS[i],
827
+ "name": m["name"],
828
+ "yaml": m["yaml"],
829
+ "vec": vec,
830
+ "preset_id": preset["id"],
831
+ })
832
+ return items
833
+
834
+
835
+ def _compute_cos_matrix(items):
836
+ """Compute cosine matrix from items (for the verdict function)."""
837
+ vecs = torch.stack([it["vec"] for it in items])
838
+ vecs_norm = vecs / vecs.norm(dim=1, keepdim=True)
839
+ return (vecs_norm @ vecs_norm.t()).numpy()
840
+
841
+
842
+ def _verdict_markdown(preset, items):
843
+ """Run the preset's verdict function on the first N items (its presets)."""
844
+ n_preset = len(preset["manifests"])
845
+ if len(items) < n_preset:
846
+ return "_(not enough manifests for verdict)_"
847
+ cos = _compute_cos_matrix(items[:n_preset])
848
+ passed, msg = preset["verdict_fn"](cos)
849
+ emoji = "βœ…" if passed else "❌"
850
+ main = f"**Verdict on preset:** {emoji} &nbsp; {msg}"
851
+ return main + _collision_note(items)
852
+
853
+
854
+ _log("Encoding preset manifests...")
855
+ PRESET_BY_ID = {p["id"]: p for p in PRESETS}
856
+ PRESET_ITEMS_BY_ID = {p["id"]: _encode_preset(p) for p in PRESETS}
857
+ for p in PRESETS:
858
+ items = PRESET_ITEMS_BY_ID[p["id"]]
859
+ cos = _compute_cos_matrix(items)
860
+ passed, _ = p["verdict_fn"](cos)
861
+ _log(f" '{p['title']}': {'PASS' if passed else 'FAIL'}")
862
+
863
+
864
  # ----- UI -----
865
 
866
  EXAMPLE_NGINX = """apiVersion: apps/v1
 
1128
  """
1129
 
1130
  _log("Building Gradio UI...")
1131
+ _TILE_CSS = """
1132
+ .demo-tile { display: flex !important; flex-direction: column !important; height: 100%; }
1133
+ .demo-tile > .prose, .demo-tile > .markdown { flex: 1 1 auto; }
1134
+ .demo-tile > button { margin-top: auto !important; }
1135
+ """
1136
  with gr.Blocks(title="YAML-BERT") as demo:
1137
  gr.Markdown(
1138
  f"""
 
1142
  Trained with MLM + reconstruction on 276K K8s manifests Β·
1143
  {n_params:,} params
1144
 
1145
+ **This Space includes 3 demos β€” pick a tab below, or use the tiles on the Overview tab.**
1146
  """
1147
  )
1148
 
 
1150
  with gr.Tab("Overview", id="overview"):
1151
  gr.Markdown("### Demos in this Space")
1152
  with gr.Row():
1153
+ with gr.Column(elem_classes="demo-tile"):
1154
  gr.Markdown(
1155
  "#### 🧩 Missing-field suggester\n"
1156
+ "Paste a YAML manifest; the model predicts which "
1157
+ "structural fields it expects but you didn't include, "
1158
+ "ranked by confidence."
 
1159
  )
1160
  open_suggester = gr.Button(
1161
  "Open missing-field suggester β†’", variant="primary"
1162
  )
1163
+ with gr.Column(elem_classes="demo-tile"):
1164
  gr.Markdown(
1165
  "#### 🌌 Manifest galaxy\n"
1166
+ "10,000 K8s manifests projected to 2D from their "
1167
+ "`doc_vec` embeddings. Kinds cluster spontaneously β€” "
1168
+ "the model was never told what `kind` is."
 
1169
  )
1170
  open_galaxy = gr.Button(
1171
  "Open manifest galaxy β†’", variant="primary"
1172
  )
1173
+ with gr.Column(elem_classes="demo-tile"):
1174
+ gr.Markdown(
1175
+ "#### πŸ”¬ Structural probes\n"
1176
+ "Preset manifest sets that test whether the model "
1177
+ "has learned specific structural distinctions, "
1178
+ "shown as a 2D layout. Add your own YAML to see "
1179
+ "where it lands."
1180
+ )
1181
+ open_probes = gr.Button(
1182
+ "Open structural probes β†’", variant="primary"
1183
+ )
1184
 
1185
  with gr.Tab("Missing-field suggester", id="suggester"):
1186
  gr.Markdown(
 
1268
  "Click a legend entry to toggle that kind on/off."
1269
  )
1270
 
1271
+ with gr.Tab("Structural probes", id="probes"):
1272
+ gr.Markdown(
1273
+ "Pick a preset that explores a specific structural claim. "
1274
+ "The 2D plane is an MDS projection of the manifests' "
1275
+ "`doc_vecs` β€” **closer = more similar**. "
1276
+ "You can also paste your own YAML to see where it lands "
1277
+ "relative to the preset."
1278
+ )
1279
+
1280
+ _initial_preset = PRESETS[0]
1281
+ _initial_items = PRESET_ITEMS_BY_ID[_initial_preset["id"]]
1282
+
1283
+ preset_dd = gr.Dropdown(
1284
+ choices=[(p["title"], p["id"]) for p in PRESETS],
1285
+ value=_initial_preset["id"],
1286
+ label="Preset",
1287
+ interactive=True,
1288
+ )
1289
+ hypothesis_md = gr.Markdown(
1290
+ value=f"**Hypothesis:** {_initial_preset['hypothesis']}"
1291
+ )
1292
+
1293
+ items_state = gr.State(value=_initial_items)
1294
+
1295
+ with gr.Row():
1296
+ with gr.Column(scale=2):
1297
+ plot = gr.Plot(
1298
+ value=_build_preset_figure(_initial_items),
1299
+ show_label=False,
1300
+ )
1301
+ verdict_md = gr.Markdown(
1302
+ value=_verdict_markdown(_initial_preset, _initial_items)
1303
+ )
1304
+
1305
+ with gr.Column(scale=1):
1306
+ gr.Markdown("**Manifests in this comparison**")
1307
+
1308
+ @gr.render(inputs=[items_state])
1309
+ def _render_accordions(items):
1310
+ if not items:
1311
+ gr.Markdown("_No manifests._")
1312
+ return
1313
+ preset_id = items[0].get("preset_id", "")
1314
+ n_preset = (len(PRESET_BY_ID[preset_id]["manifests"])
1315
+ if preset_id in PRESET_BY_ID else 0)
1316
+ for i, it in enumerate(items):
1317
+ is_user = i >= n_preset
1318
+ label = f"[{it['letter']}] {it['name']}"
1319
+ if is_user:
1320
+ label += " Β· added"
1321
+ with gr.Accordion(label, open=False):
1322
+ gr.Code(
1323
+ value=it["yaml"], language="yaml",
1324
+ lines=12, interactive=False,
1325
+ )
1326
+ if is_user:
1327
+ rm = gr.Button(
1328
+ f"Remove {it['letter']}",
1329
+ variant="secondary",
1330
+ )
1331
+
1332
+ def _remove(state, idx=i):
1333
+ new = state[:idx] + state[idx + 1:]
1334
+ preset = PRESET_BY_ID.get(
1335
+ new[0]["preset_id"]) if new else None
1336
+ verdict = (_verdict_markdown(preset, new)
1337
+ if preset else "")
1338
+ return (new,
1339
+ _build_preset_figure(new),
1340
+ verdict)
1341
+ rm.click(
1342
+ _remove,
1343
+ inputs=[items_state],
1344
+ outputs=[items_state, plot, verdict_md],
1345
+ )
1346
+
1347
+ gr.Markdown("---")
1348
+ with gr.Accordion("βž• Add your own YAML", open=False):
1349
+ new_yaml = gr.Code(
1350
+ language="yaml", lines=10,
1351
+ label="Paste a K8s manifest",
1352
+ )
1353
+ add_btn = gr.Button(
1354
+ "Encode and add to comparison", variant="primary",
1355
+ )
1356
+ add_err = gr.Markdown("")
1357
+
1358
+ def _on_add(state, yaml_text):
1359
+ if not yaml_text or not yaml_text.strip():
1360
+ return state, _build_preset_figure(state), \
1361
+ _verdict_markdown_for(state), \
1362
+ "_Empty YAML β€” nothing to add._"
1363
+ if len(state) >= len(_PRESET_LETTERS):
1364
+ return state, _build_preset_figure(state), \
1365
+ _verdict_markdown_for(state), \
1366
+ f"_Max {len(_PRESET_LETTERS)} manifests at once._"
1367
+ try:
1368
+ vec = _encode_doc_vec(yaml_text)
1369
+ except Exception as e:
1370
+ return state, _build_preset_figure(state), \
1371
+ _verdict_markdown_for(state), \
1372
+ f"_Encoding failed: `{type(e).__name__}: {e}`_"
1373
+ from yaml_bert.types import _extract_kind
1374
+ nodes = _LINEARIZER.linearize(yaml_text)
1375
+ kind = _extract_kind(nodes) or "?"
1376
+ preset_id = state[0]["preset_id"] if state else ""
1377
+ new_item = {
1378
+ "letter": _PRESET_LETTERS[len(state)],
1379
+ "name": f"{kind} (added)",
1380
+ "yaml": yaml_text,
1381
+ "vec": vec,
1382
+ "preset_id": preset_id,
1383
+ }
1384
+ new_state = state + [new_item]
1385
+ return (new_state,
1386
+ _build_preset_figure(new_state),
1387
+ _verdict_markdown_for(new_state),
1388
+ "")
1389
+
1390
+ def _verdict_markdown_for(state):
1391
+ if not state:
1392
+ return ""
1393
+ preset = PRESET_BY_ID.get(state[0].get("preset_id", ""))
1394
+ return _verdict_markdown(preset, state) if preset else ""
1395
+
1396
+ def _on_preset_change(preset_id):
1397
+ if preset_id not in PRESET_BY_ID:
1398
+ return gr.update(), gr.update(), gr.update(), gr.update()
1399
+ preset = PRESET_BY_ID[preset_id]
1400
+ items = PRESET_ITEMS_BY_ID[preset_id]
1401
+ return (items,
1402
+ _build_preset_figure(items),
1403
+ f"**Hypothesis:** {preset['hypothesis']}",
1404
+ _verdict_markdown(preset, items))
1405
+
1406
+ preset_dd.change(
1407
+ _on_preset_change,
1408
+ inputs=[preset_dd],
1409
+ outputs=[items_state, plot, hypothesis_md, verdict_md],
1410
+ )
1411
+ add_btn.click(
1412
+ _on_add,
1413
+ inputs=[items_state, new_yaml],
1414
+ outputs=[items_state, plot, verdict_md, add_err],
1415
+ )
1416
+
1417
  open_suggester.click(lambda: gr.Tabs(selected="suggester"), outputs=tabs)
1418
  open_galaxy.click(lambda: gr.Tabs(selected="galaxy"), outputs=tabs)
1419
+ open_probes.click(lambda: gr.Tabs(selected="probes"), outputs=tabs)
1420
 
1421
 
1422
  _log("Gradio UI built β€” launching")
1423
 
1424
  if __name__ == "__main__":
1425
+ demo.launch(css=_TILE_CSS)