claude-turing 4.1.0 → 4.3.0

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.
@@ -18,6 +18,8 @@ import sys
18
18
  from datetime import datetime, timezone
19
19
  from pathlib import Path
20
20
 
21
+ import yaml
22
+
21
23
  from scripts.turing_io import load_config, load_experiments
22
24
 
23
25
 
@@ -93,22 +95,113 @@ def load_model_contract(contract_path: str) -> dict:
93
95
  return {"version": version, "bundle_format": bundle_format, "raw": text}
94
96
 
95
97
 
98
+ def load_registry_status(registry_path: str = "experiments/registry.yaml") -> dict | None:
99
+ """Load registry status for the best model."""
100
+ path = Path(registry_path)
101
+ if not path.exists():
102
+ return None
103
+ try:
104
+ with open(path) as f:
105
+ data = yaml.safe_load(f)
106
+ if isinstance(data, dict) and data.get("models"):
107
+ return data
108
+ except (Exception,):
109
+ pass
110
+ return None
111
+
112
+
113
+ def compute_fairness_metrics(
114
+ predictions: list | None = None,
115
+ labels: list | None = None,
116
+ protected_attribute: list | None = None,
117
+ group_names: list[str] | None = None,
118
+ ) -> dict | None:
119
+ """Compute demographic parity and equal opportunity metrics.
120
+
121
+ Args:
122
+ predictions: Model predictions.
123
+ labels: True labels.
124
+ protected_attribute: Group membership for each sample.
125
+ group_names: Names of groups.
126
+
127
+ Returns:
128
+ Fairness metrics dict or None if insufficient data.
129
+ """
130
+ if predictions is None or protected_attribute is None:
131
+ return None
132
+ if len(predictions) != len(protected_attribute):
133
+ return None
134
+ if len(predictions) == 0:
135
+ return None
136
+
137
+ import numpy as np
138
+
139
+ preds = np.array(predictions)
140
+ groups = np.array(protected_attribute)
141
+ unique_groups = sorted(set(groups))
142
+
143
+ if group_names is None:
144
+ group_names = [str(g) for g in unique_groups]
145
+
146
+ # Demographic parity: P(Y_hat=1 | G=g) for each group
147
+ group_positive_rates = {}
148
+ for g, name in zip(unique_groups, group_names):
149
+ mask = groups == g
150
+ if mask.sum() == 0:
151
+ continue
152
+ rate = float(preds[mask].mean()) if preds[mask].size > 0 else 0
153
+ group_positive_rates[name] = round(rate, 4)
154
+
155
+ # Demographic parity difference
156
+ rates = list(group_positive_rates.values())
157
+ dp_diff = round(max(rates) - min(rates), 4) if len(rates) >= 2 else 0
158
+
159
+ result = {
160
+ "group_positive_rates": group_positive_rates,
161
+ "demographic_parity_difference": dp_diff,
162
+ "n_groups": len(unique_groups),
163
+ }
164
+
165
+ # Equal opportunity (if labels available): P(Y_hat=1 | Y=1, G=g)
166
+ if labels is not None and len(labels) == len(predictions):
167
+ labs = np.array(labels)
168
+ group_tpr = {}
169
+ for g, name in zip(unique_groups, group_names):
170
+ mask = (groups == g) & (labs == 1)
171
+ if mask.sum() == 0:
172
+ continue
173
+ tpr = float(preds[mask].mean()) if preds[mask].size > 0 else 0
174
+ group_tpr[name] = round(tpr, 4)
175
+
176
+ result["group_true_positive_rates"] = group_tpr
177
+ tpr_vals = list(group_tpr.values())
178
+ result["equal_opportunity_difference"] = round(max(tpr_vals) - min(tpr_vals), 4) if len(tpr_vals) >= 2 else 0
179
+
180
+ return result
181
+
182
+
96
183
  def generate_card(
97
184
  config_path: str = "config.yaml",
98
185
  log_path: str = "experiments/log.jsonl",
99
186
  contract_path: str = "model_contract.md",
100
187
  output_path: str | None = None,
188
+ include_fairness: bool = False,
189
+ fairness_data: dict | None = None,
190
+ registry_path: str = "experiments/registry.yaml",
101
191
  ) -> str:
102
192
  """Produce a model card markdown document.
103
193
 
104
194
  Combines information from the project config, experiment log,
105
- and model contract into a standardized model card.
195
+ model contract, registry, and optional fairness data.
106
196
 
107
197
  Args:
108
198
  config_path: Path to config.yaml.
109
199
  log_path: Path to experiments/log.jsonl.
110
200
  contract_path: Path to model_contract.md.
111
201
  output_path: If given, write the card to this file.
202
+ include_fairness: If True, add fairness section.
203
+ fairness_data: Pre-computed fairness data {predictions, labels, protected_attribute}.
204
+ registry_path: Path to registry YAML.
112
205
 
113
206
  Returns:
114
207
  The model card as a markdown string.
@@ -247,7 +340,6 @@ def generate_card(
247
340
  if best:
248
341
  seed_study_path = Path("experiments/seed_studies") / f"{best.get('experiment_id', 'unknown')}-seeds.yaml"
249
342
  if seed_study_path.exists():
250
- import yaml
251
343
  with open(seed_study_path) as f:
252
344
  seed_study = yaml.safe_load(f) or {}
253
345
  if seed_study and "mean" in seed_study:
@@ -306,6 +398,57 @@ def generate_card(
306
398
  "- Not intended for: <placeholder for user to fill>",
307
399
  ])
308
400
 
401
+ # --- Registry Status ---
402
+ registry_data = load_registry_status(registry_path)
403
+ if registry_data and best:
404
+ exp_id = best.get("experiment_id", "")
405
+ for model in registry_data.get("models", []):
406
+ if model.get("exp_id") == exp_id:
407
+ lines.extend([
408
+ "",
409
+ "## Registry Status",
410
+ "",
411
+ f"- **Stage:** {model.get('stage', 'unregistered')}",
412
+ f"- **Version:** {model.get('version', 'N/A')}",
413
+ f"- **Registered:** {model.get('registered_at', 'N/A')[:10]}",
414
+ f"- **Gates passed:** {', '.join(model.get('gates_passed', [])) or 'none'}",
415
+ ])
416
+ break
417
+
418
+ # --- Fairness ---
419
+ if include_fairness:
420
+ lines.extend([
421
+ "",
422
+ "## Fairness Analysis",
423
+ "",
424
+ ])
425
+ if fairness_data:
426
+ fairness = compute_fairness_metrics(
427
+ predictions=fairness_data.get("predictions"),
428
+ labels=fairness_data.get("labels"),
429
+ protected_attribute=fairness_data.get("protected_attribute"),
430
+ group_names=fairness_data.get("group_names"),
431
+ )
432
+ if fairness:
433
+ lines.append("### Demographic Parity")
434
+ lines.append("")
435
+ for group, rate in fairness.get("group_positive_rates", {}).items():
436
+ lines.append(f"- **{group}:** {rate:.4f}")
437
+ lines.append(f"- **Parity difference:** {fairness['demographic_parity_difference']:.4f}")
438
+
439
+ if "group_true_positive_rates" in fairness:
440
+ lines.append("")
441
+ lines.append("### Equal Opportunity")
442
+ lines.append("")
443
+ for group, tpr in fairness["group_true_positive_rates"].items():
444
+ lines.append(f"- **{group}:** {tpr:.4f}")
445
+ lines.append(f"- **Opportunity difference:** {fairness['equal_opportunity_difference']:.4f}")
446
+ else:
447
+ lines.append("- Fairness analysis requested but insufficient data provided")
448
+ else:
449
+ lines.append("- Fairness analysis requested but no protected attribute data available")
450
+ lines.append("- Provide `--fairness-data` with predictions, labels, and protected attributes")
451
+
309
452
  # --- Ethical Considerations ---
310
453
  lines.extend([
311
454
  "",
@@ -354,9 +497,17 @@ def main() -> None:
354
497
  parser.add_argument("--log", default="experiments/log.jsonl", help="Path to experiment log")
355
498
  parser.add_argument("--contract", default="model_contract.md", help="Path to model contract")
356
499
  parser.add_argument("--output", default=None, help="Output path (default: print to stdout)")
500
+ parser.add_argument("--include", default=None, help="Include extra sections (e.g., 'fairness')")
501
+ parser.add_argument("--registry", default="experiments/registry.yaml", help="Path to model registry")
357
502
  args = parser.parse_args()
358
503
 
359
- card = generate_card(args.config, args.log, args.contract, args.output)
504
+ include_fairness = args.include and "fairness" in args.include
505
+
506
+ card = generate_card(
507
+ args.config, args.log, args.contract, args.output,
508
+ include_fairness=include_fairness,
509
+ registry_path=args.registry,
510
+ )
360
511
  if args.output:
361
512
  print(f"Model card written to {args.output}")
362
513
  else: