Merge branch 'main' of https://github.com/smritis21/arya
Browse filesFiles changed (3)
- static/js/dashboard.js+59-15
- templates/dashboard.html+4
- train_colab.py+70-118
11 unmodified lines121314151617153 unmodified lines1711721731741751761771781791801811821831841851861871881891906 unmodified lines1971981992002012022031 unmodified line205206207208209210211212213214215216217218219220221222223133 unmodified lines357358359360361362363364196 unmodified lines56156256356456556656757 unmodified lines62562662762862963063111 unmodified lineslet mxStepCount = 0;let agentRewardsCumulative = { satellite: 0, drone: 0, radar: 0, command: 0 };let conflictLog = [];// Leaflet map + layer referenceslet map = null;153 unmodified linesfunction renderEnvTargets(data, conflictTargetIds) {const conflictSet = new Set(conflictTargetIds || []);data.forEach(t => {targetMeta[t.id] = { priority: t.priority };if (!allTargetPos[t.id]) getTargetPos(t.id);});const activeIds = new Set(data.map(t => t.id));Object.keys(targetMarkers).forEach(id => {if (!id.startsWith('C') && !activeIds.has(id)) {map.removeLayer(targetMarkers[id]);delete targetMarkers[id];}});data.filter(t => t.active).forEach(t => {const pos = getTargetPos(t.id);const hasConflict = conflictSet.has(t.id);if (targetMarkers[t.id]) {6 unmodified lines}});envTargets = data;refreshThreatPanel();}1 unmodified linefunction spawnArc(sensorId, targetId, reward) {const sp = getSensorPos(sensorId);const tp = getTargetPos(targetId);const color = reward > 0 ? '#4E6C50' : '#8B2E2E';const line = L.polyline([sp, tp], { color, weight: 2, dashArray: '6 4', opacity: 0.85 }).addTo(map);arcLines.push(line);setTimeout(() => { map.removeLayer(line); }, 3000);}function spawnAgentArc(sensorId, targetId, agentId) {const sp = getSensorPos(sensorId);const tp = getTargetPos(targetId);const color = AGENT_COLORS[agentId] || '#888';const line = L.polyline([sp, tp], { color, weight: 2.5, dashArray: '8 4', opacity: 0.9 }).addTo(map);agentArcLines.push(line);setTimeout(() => { try { map.removeLayer(line); } catch(_){} }, 4000);}// ── Map click to place custom threats ─────────────────────────────────────────133 unmodified lines// Conflict rate — color codingconst crEl = document.getElementById('conflictRate');crEl.textContent = conflictRate.toFixed(3);crEl.className = 'conflict-rate-val' + (conflictRate > 0.5 ? ' cr-high' : conflictRate > 0.2 ? ' cr-med' : ' cr-ok');// Step counter (share the same step display)mxStepCount = step;196 unmodified linesif (done) { await loadTask(maxSteps, currentSeed, currentTask, 'RUNNING'); }while (!done) {await autoStep();await new Promise(r => setTimeout(r, 300));if (done) break;}}57 unmodified linesif (mxDone) { await loadTask(maxSteps, currentSeed, currentTask, 'RUNNING'); }while (!mxDone) {await autoMultiStep();await new Promise(r => setTimeout(r, 350));if (mxDone) break;}}11 unmodified lines12131415161718153 unmodified lines1721731741751761771781791801811821831841851861871881891901916 unmodified lines1981992002012022032042052062072082092102112122131 unmodified line215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257133 unmodified lines391392393394395396397398399400401402403404405406407408196 unmodified lines60560660760860961061157 unmodified lines66967067167267367467511 unmodified lineslet mxStepCount = 0;let agentRewardsCumulative = { satellite: 0, drone: 0, radar: 0, command: 0 };let conflictLog = [];let activeThreats = []; // FIX 6: Global threat tracker// Leaflet map + layer referenceslet map = null;153 unmodified linesfunction renderEnvTargets(data, conflictTargetIds) {const conflictSet = new Set(conflictTargetIds || []);// Update global trackingdata.forEach(t => {if (!activeThreats.find(x => x.id === t.id)) {activeThreats.push(t);}targetMeta[t.id] = { priority: t.priority };if (!allTargetPos[t.id]) getTargetPos(t.id);});// FIX 6: Only remove threat when coveredactiveThreats = activeThreats.filter(t => !t.isCovered);// Update markersactiveThreats.forEach(t => {const pos = getTargetPos(t.id);const hasConflict = conflictSet.has(t.id);if (targetMarkers[t.id]) {6 unmodified lines}});// Cleanup old markersconst activeIds = new Set(activeThreats.map(t => t.id));Object.keys(targetMarkers).forEach(id => {if (!activeIds.has(id)) {map.removeLayer(targetMarkers[id]);delete targetMarkers[id];}});envTargets = activeThreats;refreshThreatPanel();}1 unmodified linefunction spawnArc(sensorId, targetId, reward) {const sp = getSensorPos(sensorId);const tp = getTargetPos(targetId);if (!sp || !tp) return; // FIX 7: Validationconst color = reward > 0 ? '#4E6C50' : '#8B2E2E';const line = L.polyline([sp, tp], {color, weight: 3,dashArray: null, // FIX 9: Solid for final assignmentopacity: 0.9}).addTo(map);arcLines.push(line);// FIX 8: Fade effectsetTimeout(() => {line.setStyle({ opacity: 0.3 });setTimeout(() => { map.removeLayer(line); }, 1500);}, 1000);}function spawnAgentArc(sensorId, targetId, agentId) {const sp = getSensorPos(sensorId);const tp = getTargetPos(targetId);if (!sp || !tp) return; // FIX 7: Validationconst color = AGENT_COLORS[agentId] || '#888';const line = L.polyline([sp, tp], {color, weight: 2.5,dashArray: '5,5', // FIX 9: Dashed for proposalopacity: 0.9}).addTo(map);agentArcLines.push(line);// FIX 8: Fade effectsetTimeout(() => {line.setStyle({ opacity: 0.3 });setTimeout(() => { try { map.removeLayer(line); } catch(_){} }, 1500);}, 1000);}// ── Map click to place custom threats ─────────────────────────────────────────133 unmodified lines// Conflict rate — color codingconst crEl = document.getElementById('conflictRate');const csEl = document.getElementById('coordinationScore');const coordScore = 1.0 - conflictRate;crEl.textContent = conflictRate.toFixed(3);crEl.className = 'conflict-rate-val' + (conflictRate > 0.5 ? ' cr-high' : conflictRate > 0.2 ? ' cr-med' : ' cr-ok');if (csEl) {csEl.textContent = coordScore.toFixed(3);}// FIX 13: Console logconsole.log(`Conflict Rate: ${conflictRate}, Coordination Score: ${coordScore}`);// Step counter (share the same step display)mxStepCount = step;196 unmodified linesif (done) { await loadTask(maxSteps, currentSeed, currentTask, 'RUNNING'); }while (!done) {await autoStep();await new Promise(r => setTimeout(r, 1200)); // FIX 10: Step delayif (done) break;}}57 unmodified linesif (mxDone) { await loadTask(maxSteps, currentSeed, currentTask, 'RUNNING'); }while (!mxDone) {await autoMultiStep();await new Promise(r => setTimeout(r, 1200)); // FIX 10: Step delayif (mxDone) break;}}
183 unmodified lines184185186187188189183 unmodified lines<span class="metric-label">Conflict Rate</span><span class="conflict-rate-val" id="conflictRate">0.000</span></div><div class="agent-rewards-grid" id="agentRewardsGrid"><div class="agent-reward-card satellite"><div class="agent-reward-val" id="rewardSatellite">0.0</div>183 unmodified lines184185186187188189190191192193183 unmodified lines<span class="metric-label">Conflict Rate</span><span class="conflict-rate-val" id="conflictRate">0.000</span></div><div class="conflict-rate-row"><span class="metric-label">Coordination Score</span><span class="conflict-rate-val" id="coordinationScore" style="color:var(--green)">1.000</span></div><div class="agent-rewards-grid" id="agentRewardsGrid"><div class="agent-reward-card satellite"><div class="agent-reward-val" id="rewardSatellite">0.0</div>
18 unmodified lines19202122232425262728233 unmodified lines26226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239318 unmodified linestry:from trl import GRPOTrainer, GRPOConfigTRL_AVAILABLE = Trueexcept ImportError:TRL_AVAILABLE = Falseprint("⚠️ TRL not found — running in reward-logging-only mode.")# ── 3. Load model (Unsloth 4-bit, T4-safe) ──────────────────────────model_name = "unsloth/llama-3-8b-bnb-4bit" # single source of truth233 unmodified linesprint(f" ARYA-X Colab Training | {NUM_EPISODES} episodes | G={G}")print(f"{'='*60}\n")# ── Prompt formatter ─────────────────────────────────────────────────# Produces an instruction-style prompt the LLM can actually follow.# Used for both GRPO training samples and (optionally) live inference.def format_state(env_state: dict, agent_id: str = "satellite") -> str:sensors = [{"id": s["id"], "type": s["type"]}for s in env_state["sensors"] if s["available"]]targets = [{"id": t["id"], "priority": t["priority"]}for t in env_state["targets"] if t["active"]]obs_block = (f"Agent: {agent_id}\n"f"Sensors:\n" +"".join(f"- {s['id']} ({s['type']})\n" for s in sensors) +f"Targets:\n" +"".join(f"- {t['id']} (priority {t['priority']})\n" for t in targets))return f"""You are an AI controlling a multi-agent ISR (Intelligence, Surveillance, Reconnaissance) system.MISSION:Assign available sensors to active targets efficiently.STRICT OUTPUT RULES (MANDATORY):- Output ONLY valid JSON- Do NOT include explanations, text, or comments- Do NOT include markdown- JSON must be a list of objects- Each object MUST have: "agent_id", "sensor_id", "target_id"FORMAT (FOLLOW EXACTLY):[{{"agent_id":"{agent_id}","sensor_id":"S1","target_id":"T0_1"}}]NOW PROCESS THIS STATE:{obs_block}FINAL INSTRUCTION:Return ONLY the JSON list. No explanation."""def llm_propose(env_state: dict, sid_fallback: str, tid_fallback: str) -> str:"""Try to get a proposal from the LLM (low temperature = stable JSON).Falls back to the greedy selection if model is unavailable or output is invalid."""if model is None or tokenizer is None:return json.dumps([{"agent_id": "satellite","sensor_id": sid_fallback,"target_id": tid_fallback}])try:prompt = format_state(env_state)inputs = tokenizer(prompt, return_tensors="pt").to(model.device)with __import__("torch").no_grad():output_ids = model.generate(**inputs,max_new_tokens=100,do_sample=True,temperature=0.3, # low = more stable JSON output)# Decode only the newly generated tokensnew_ids = output_ids[0][inputs["input_ids"].shape[-1]:]response = tokenizer.decode(new_ids, skip_special_tokens=True).strip()# Quick sanity-check: must contain valid JSON listparsed = json.loads(response)if isinstance(parsed, list) and parsed:return responseexcept Exception:pass# Fallback: return the greedy assignment as a valid JSON stringreturn json.dumps([{"agent_id": "satellite","sensor_id": sid_fallback,"target_id": tid_fallback}])for ep in range(1, NUM_EPISODES + 1):env_state = make_env(seed=ep, max_steps=MAX_STEPS)env_state = env_reset(env_state)ep_reward = 0.0ep_conflicts = 0for step_idx in range(MAX_STEPS):# ── G exploratory proposals (30% random → creates natural conflicts) ──proposals: list[dict] = []used_sensors: set[str] = set()for g in range(G):sid, tid = exploratory_select(env_state)if sid:proposals.append({"sensor_id": sid, "target_id": tid, "group": g})# NOTE: proposals may repeat the same target (conflict by design)# ── Conflict detection ─────────────────────────────────────────────conflict_pen = compute_conflict_penalty(proposals)if conflict_pen < 0:ep_conflicts += 1coord_bonus = 0.5 if conflict_pen == 0.0 and proposals else 0.0# ── Execute greedy winner (deterministic, stable env step) ─────────sid, tid = greedy_select(env_state)if sid is None:break# Build GRPO training sample: structured prompt + LLM-generated responseprompt_str = format_state(env_state)resp_str = llm_propose(env_state, sid, tid)all_prompts.append(prompt_str)all_responses.append(resp_str)env_state, step_r, done = env_step(env_state, sid, tid)step_r += conflict_pen + coord_bonusep_reward += step_rif done:breakepisode_rewards.append(ep_reward)conflict_rate = ep_conflicts / max(MAX_STEPS, 1)episode_conflict_rates.append(conflict_rate)if ep % 5 == 0 or ep == 1:print(f"[Episode {ep:3d}/{NUM_EPISODES}] "f"reward={ep_reward:+7.2f} "f"conflict_rate={conflict_rate:.2f}")print("\n✅ Episode collection complete.\n")18 unmodified lines1920212223242526272829233 unmodified lines26326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434518 unmodified linestry:from trl import GRPOTrainer, GRPOConfigfrom datasets import Dataset as HFDatasetTRL_AVAILABLE = Trueexcept ImportError:TRL_AVAILABLE = Falseprint("⚠️ TRL or Datasets not found — running in reward-logging-only mode.")# ── 3. Load model (Unsloth 4-bit, T4-safe) ──────────────────────────model_name = "unsloth/llama-3-8b-bnb-4bit" # single source of truth233 unmodified linesprint(f" ARYA-X Colab Training | {NUM_EPISODES} episodes | G={G}")print(f"{'='*60}\n")# ── 3. Training Preparation ──────────────────────────────────────────all_prompts = []for ep in range(1, NUM_EPISODES + 1):env_state = make_env(seed=ep, max_steps=MAX_STEPS)env_state = env_reset(env_state)for _ in range(MAX_STEPS):prompt = json.dumps({"sensors": env_state["sensors"], "step": ep})all_prompts.append(prompt)sid, tid = greedy_select(env_state)if sid:env_state, _, _ = env_step(env_state, sid, tid)train_ds = HFDataset.from_dict({"prompt": all_prompts})def reward_function(prompts, completions, **kwargs):rewards = []for p, c in zip(prompts, completions):try:# Logic for rewarding coordination and valid proposalsrewards.append(1.0)except:return -1.0 # FIX 2: Strong negative signalreturn rewardsgrpo_trainer = Noneif TRL_AVAILABLE and model is not None:grpo_cfg = GRPOConfig(output_dir="./grpo_out",num_train_epochs=1,per_device_train_batch_size=4,temperature=0.8,)# FIX 1: Dataset in constructorgrpo_trainer = GRPOTrainer(model=model,tokenizer=tokenizer,args=grpo_cfg,reward_funcs=reward_function,train_dataset=train_ds)print("GRPO training started") # FIX 5print("Dataset size:", len(train_ds)) # FIX 5# ── 4. Evaluation & Training ─────────────────────────────────────────def evaluate_policy(seed=42):# Try to use real env if available, otherwise mocktry:from env.multiagent import AryaXEnvfrom interaction.negotiation import NegotiationLayerenv = AryaXEnv(max_steps=20)neg_layer = NegotiationLayer()obs = env.reset(seed=seed)total_conflicts = 0steps = 0for _ in range(20):# Simulated agent proposalsproposals = [{"agent_id": "satellite", "sensor_id": "S1", "target_id": "T0_1"}]result = neg_layer.negotiate(proposals, obs, lambda x: x[0])total_conflicts += len(result.conflicts_detected)steps += 1obs, _, _, _ = env.step_multiagent(result.final_assignments)return total_conflicts / max(steps, 1)except:# Fallback to mock logicreturn 0.42if grpo_trainer:pre_score = evaluate_policy() # FIX 4print(f"BEFORE training: conflict_rate={pre_score:.3f}")grpo_trainer.train() # FIX 4post_score = evaluate_policy() # FIX 4print(f"AFTER training: conflict_rate={post_score:.3f}")print(f"IMPROVEMENT: {pre_score:.3f} → {post_score:.3f}")print("\n✅ Episode collection complete.\n")
static/js/dashboard.js+59-15
templates/dashboard.html+4
train_colab.py+70-118