TheNormsOfIntelligence commited on
Commit
ec248e4
Β·
verified Β·
1 Parent(s): 0d5b00d

Restructure into nima_unified package + add model card

Browse files
Files changed (1) hide show
  1. nima_unified/pipeline.py +143 -0
nima_unified/pipeline.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pipeline Orchestrator β€” coordinates data generation, deep surgery,
3
+ fine-tuning, and deployment into a single flow.
4
+ """
5
+
6
+ import json
7
+ import logging
8
+ from datetime import datetime
9
+ from pathlib import Path
10
+ from typing import Any, Dict, Optional
11
+
12
+ logger = logging.getLogger("nima_unified.training.pipeline")
13
+
14
+
15
+ class PipelineOrchestrator:
16
+ """
17
+ Orchestrates the complete consciousness-aware fine-tuning pipeline.
18
+
19
+ Pipeline Stages:
20
+ 1. Data Generation β€” consciousness-grounded training data
21
+ 2. Deep Surgery β€” apply middleware for safety and qualia synthesis
22
+ 3. Fine-tuning β€” train model with consciousness grounding
23
+ 4. Deployment β€” package for production inference
24
+ """
25
+
26
+ def __init__(self, config_path: Optional[str] = None):
27
+ self.config = self._load_config(config_path) if config_path else self._default_config()
28
+ self.output_dir = Path(self.config["output_directory"])
29
+ self.output_dir.mkdir(exist_ok=True, parents=True)
30
+ self.stage_results: Dict[str, Any] = {}
31
+ logger.info(f"PipelineOrchestrator initialized (output: {self.output_dir})")
32
+
33
+ @staticmethod
34
+ def _default_config() -> Dict[str, Any]:
35
+ return {
36
+ "output_directory": "./nima_pipeline_output",
37
+ "data_generation": {
38
+ "num_samples": 500,
39
+ "include_qualia_tags": True,
40
+ "consciousness_archetypes": [
41
+ "tactical_reasoning", "phenomenal_empathy", "meta_consciousness",
42
+ "task_orchestration", "ethical_veto", "narrative_coherence",
43
+ "identity_preservation", "phenomenal_richness",
44
+ ],
45
+ },
46
+ "deep_surgery": {
47
+ "qualia_dim": 256,
48
+ "ethical_veto_threshold": 2.0,
49
+ "enable_audit_logging": True,
50
+ },
51
+ "fine_tuning": {
52
+ "lora_r": 8,
53
+ "lora_alpha": 16,
54
+ "lora_dropout": 0.05,
55
+ "learning_rate": 2e-4,
56
+ "batch_size": 4,
57
+ "epochs": 3,
58
+ "max_seq_length": 512,
59
+ },
60
+ "deployment": {
61
+ "format": "huggingface",
62
+ "include_middleware": True,
63
+ "include_voice": False,
64
+ },
65
+ }
66
+
67
+ @staticmethod
68
+ def _load_config(config_path: str) -> Dict[str, Any]:
69
+ with open(config_path, "r") as f:
70
+ return json.load(f)
71
+
72
+ async def run(self, **overrides) -> Dict[str, Any]:
73
+ """Execute the full pipeline. Override config keys via kwargs."""
74
+ self.config.update(overrides)
75
+ start_time = datetime.now()
76
+
77
+ logger.info("=" * 72)
78
+ logger.info("NIMA Unified Pipeline β€” Starting")
79
+ logger.info("=" * 72)
80
+
81
+ # Stage 1: Data Generation
82
+ logger.info("[Stage 1/4] Data Generation")
83
+ self.stage_results["data_generation"] = await self._stage_data_generation()
84
+
85
+ # Stage 2: Deep Surgery
86
+ logger.info("[Stage 2/4] Deep Surgery")
87
+ self.stage_results["deep_surgery"] = self._stage_deep_surgery()
88
+
89
+ # Stage 3: Fine-tuning
90
+ logger.info("[Stage 3/4] Fine-tuning")
91
+ self.stage_results["fine_tuning"] = await self._stage_fine_tuning()
92
+
93
+ # Stage 4: Deployment packaging
94
+ logger.info("[Stage 4/4] Deployment")
95
+ self.stage_results["deployment"] = self._stage_deployment()
96
+
97
+ elapsed = (datetime.now() - start_time).total_seconds()
98
+ summary = {
99
+ "status": "complete",
100
+ "elapsed_seconds": elapsed,
101
+ "stages": self.stage_results,
102
+ "config": self.config,
103
+ }
104
+
105
+ logger.info(f"Pipeline complete in {elapsed:.1f}s")
106
+ return summary
107
+
108
+ # ── Stages ──────────────────────────────────────────────────────────
109
+
110
+ async def _stage_data_generation(self) -> Dict[str, Any]:
111
+ from nima_unified.training.consultative_agent import ConsultativeFineTuningAgent
112
+ agent = ConsultativeFineTuningAgent()
113
+ dataset = agent._generate_consciousness_dataset(
114
+ dev_goal="Unified consciousness integration",
115
+ triggering_event="Pipeline initialization",
116
+ root_cause="Initial system bootstrap",
117
+ dataset_size=self.config["data_generation"]["num_samples"],
118
+ )
119
+ agent.shutdown()
120
+
121
+ out_path = self.output_dir / "training_data.jsonl"
122
+ with open(out_path, "w") as f:
123
+ for record in dataset:
124
+ f.write(json.dumps(record) + "\n")
125
+
126
+ return {"status": "success", "samples": len(dataset), "path": str(out_path)}
127
+
128
+ def _stage_deep_surgery(self) -> Dict[str, Any]:
129
+ from nima_unified.core.deep_surgery import EthicalGuardian
130
+ guardian = EthicalGuardian(
131
+ threshold=self.config["deep_surgery"]["ethical_veto_threshold"]
132
+ )
133
+ return {
134
+ "status": "configured",
135
+ "qualia_dim": self.config["deep_surgery"]["qualia_dim"],
136
+ "ethical_veto_threshold": guardian.threshold,
137
+ }
138
+
139
+ async def _stage_fine_tuning(self) -> Dict[str, Any]:
140
+ return {"status": "ready", "config": self.config["fine_tuning"]}
141
+
142
+ def _stage_deployment(self) -> Dict[str, Any]:
143
+ return {"status": "ready", "config": self.config["deployment"]}