nsdl / app.py
multimodalart's picture
multimodalart HF Staff
Upload app.py with huggingface_hub
843c25f verified
Raw History Blame Contribute Delete
24.2 kB
"""NSDL: Neuro-Symbolic Division of Labor for Multi-Robot Task Planning.
Interactive demo of the L-NSDL agentic pipeline (paper 2611.16671):
a fine-tuned Qwen2.5-VL 7B planner emits goal / assignment / plan-sketch /
tool-call / plan blocks, deterministic neuro-symbolic tools (schedule,
verify, detect, expand, lookup) execute between rounds, and the final plan
is lowered to a dependency graph, executor assignment, and dispatchable
micro-steps.
The pipeline ported here follows scripts/eval_lnsdl_agentic_viki_l2.py
(run_agentic_sample) at the reference defaults: max_tool_rounds=3,
max_new_tokens=4096, temperature=0 (greedy), detector backend
ultralytics_yolo26 with conf 0.25 / iou 0.70 / max_det 64.
"""
from __future__ import annotations
import json
import os
import time
from pathlib import Path
from typing import Any
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import spaces # noqa: E402 (must precede torch/CUDA imports)
import gradio as gr # noqa: E402
# --- vendored NSDL runtime (imported before torch; chain is torch-free) ------
from nsdl.aig_builder import build_affordance_context
from nsdl.dispatcher import dispatch_graph
from nsdl.macro_graph import _assign_executors_to_graph, collect_selected_robot_types
from nsdl.scene_facts_refiner import build_scene_facts_refiner
from nsdl.scene_parser import build_scene_parser
from nsdl.schema import BenchmarkSample, DispatcherPayload, PipelineResult
from nsdl.slm_interface import (
SLMResponse,
convert_operations_to_graph_plan,
validate_operations,
)
from nsdl.tool_runtime import (
ToolRuntimeLoopResult,
_jsonable,
run_agentic_tool_loop,
slm_response_to_dict,
)
from nsdl.yolo_detector import DEFAULT_DETECTOR_BACKEND, build_structured_detector
from nsdl.profiles import VIKI_L2_PROFILE, use_benchmark_profile
PLANNER_ID = os.environ.get("NSDL_PLANNER_ID", "XinchengTan/nsdl-7b-rl-viki")
DETECTOR_ID = os.environ.get("NSDL_DETECTOR_ID", "XinchengTan/nsdl-detector-viki20")
# Reference defaults from scripts/eval_lnsdl_agentic_viki_l2.py.
MAX_TOOL_ROUNDS = 3
MAX_NEW_TOKENS = 4096
TEMPERATURE = 0.0
DETECTOR_CONF = 0.25
DETECTOR_IOU = 0.70
DETECTOR_MAX_DET = 64
ROBOT_TYPES = ["unitree_h1", "fetch", "stompy", "panda", "anymal_c", "unitree_go2"]
# ----------------------------------------------------------------------------
# Model loading (module scope, eager, on cuda)
# ----------------------------------------------------------------------------
def _download_detector_weights() -> str:
from huggingface_hub import hf_hub_download
path = hf_hub_download(DETECTOR_ID, "best.pt")
print(f"[nsdl] detector weights: {path}", flush=True)
return path
def _load_backend():
from nsdl.slm_backends import get_local_vl_backend
from nsdl.slm_backends.local_vl import load_local_vlm
print(f"[nsdl] loading planner {PLANNER_ID} ...", flush=True)
load_local_vlm(PLANNER_ID, device="cuda")
print("[nsdl] planner loaded.", flush=True)
return get_local_vl_backend()
BACKEND = _load_backend()
DETECTOR_WEIGHTS = _download_detector_weights()
DETECTOR = build_structured_detector(
DEFAULT_DETECTOR_BACKEND,
weights_path=DETECTOR_WEIGHTS,
confidence_threshold=DETECTOR_CONF,
iou_threshold=DETECTOR_IOU,
max_det=DETECTOR_MAX_DET,
)
# Eager warmup: loads YOLO into memory now so the first GPU call does not pay
# the ultralytics import + weight-load inside the duration budget.
DETECTOR.warmup()
print("[nsdl] detector warmed up.", flush=True)
SCENE_PARSER = build_scene_parser("rule")
SCENE_REFINER = build_scene_facts_refiner("none")
# ----------------------------------------------------------------------------
# Trace helpers (ported from scripts/eval_lnsdl_agentic_viki_l2.py)
# ----------------------------------------------------------------------------
def _json_fallback(obj: Any) -> str:
if type(obj).__module__.split(".", 1)[0] == "PIL":
return "<image>"
return str(obj)
def _goal_active(response: SLMResponse) -> list[str] | None:
goal = response.goal
if not isinstance(goal, dict):
return None
active = goal.get("active")
if not isinstance(active, list):
return None
return [str(item) for item in active if str(item).strip()]
def flatten_tool_events(loop: ToolRuntimeLoopResult) -> list[dict[str, Any]]:
events: list[dict[str, Any]] = []
for turn in loop.events:
if not isinstance(turn, dict):
continue
calls = turn.get("tool_calls", [])
results = turn.get("tool_results", [])
if not isinstance(calls, list):
calls = []
if not isinstance(results, list):
results = []
for index, call in enumerate(calls):
result = results[index] if index < len(results) else None
name = call.get("name") if isinstance(call, dict) else None
events.append({
"round": turn.get("round"),
"index": index,
"name": str(name or ""),
"call": call,
"result": result,
"result_ok": result.get("ok") if isinstance(result, dict) else None,
"executed": result is not None,
})
return events
def loop_to_trace(loop: ToolRuntimeLoopResult) -> dict[str, Any]:
assistant_turns = [
str(message.get("content") or "")
for message in loop.messages
if str(message.get("role")) == "assistant"
]
initial_messages = loop.messages[:2]
system_prompt = str(initial_messages[0].get("content") or "") if initial_messages else ""
user_prompt = str(initial_messages[1].get("content") or "") if len(initial_messages) > 1 else ""
tool_events = flatten_tool_events(loop)
executed_tool_events = [event for event in tool_events if event.get("executed")]
tool_names = [str(event.get("name") or "tool") for event in executed_tool_events]
parse_diagnostics = [
diagnostic
for event in loop.events
for diagnostic in event.get("parsed", {}).get("parse_diagnostics", [])
if isinstance(diagnostic, dict)
]
return {
"schema_version": 2,
"stopped_reason": loop.stopped_reason,
"rounds": loop.rounds,
"input": {
"system_prompt_chars": len(system_prompt),
"user_prompt": user_prompt,
},
"assistant_turn_count": len(assistant_turns),
"final_raw_text": loop.raw_text,
"final_response": slm_response_to_dict(loop.response),
"parse_diagnostics": parse_diagnostics,
"emitted_tool_call_count": sum(
len(event.get("tool_calls", []))
for event in loop.events
if isinstance(event, dict)
),
"executed_tool_call_count": len(executed_tool_events),
"tool_names": tool_names,
"tool_results": [_jsonable(result) for result in loop.tool_results],
"final_plan_op_count": len(loop.response.operations),
}
# ----------------------------------------------------------------------------
# Pipeline (port of run_agentic_sample, reference defaults)
# ----------------------------------------------------------------------------
class PlanRejected(RuntimeError):
"""The neuro-symbolic validator rejected the planner's operations.
This is a normal NSDL outcome (the symbolic layer catching an invalid
plan), so it is surfaced as a structured output rather than a crash.
"""
def __init__(self, messages: list[str], trace: dict[str, Any]):
self.messages = list(messages)
self.trace = trace
super().__init__("; ".join(self.messages) or "operation validation failed")
def _empty_result(sample: BenchmarkSample, scene_facts: Any) -> PipelineResult:
from nsdl.schema import GraphPlan
return PipelineResult(
sample=sample,
initial_scene_facts=scene_facts,
scene_facts=scene_facts,
yolo_detections=None,
graph_plan=GraphPlan(
task_family=None,
build_mode="lnsdl_agentic_tool_loop",
family_shortcut_used=False,
nodes=[],
compiler_notes=[],
builder_trace={},
),
selected_robot_types=[],
micro_steps=[],
dispatcher_output=None,
)
def _run_pipeline(
sample: BenchmarkSample, max_tool_rounds: int = MAX_TOOL_ROUNDS
) -> tuple[PipelineResult, dict[str, Any]]:
with use_benchmark_profile(VIKI_L2_PROFILE):
initial_scene_facts = SCENE_PARSER.parse(sample)
scene_facts = SCENE_REFINER.refine(sample, initial_scene_facts, yolo_detections=None)
affordance_context = build_affordance_context(scene_facts)
loop = run_agentic_tool_loop(
BACKEND,
scene_facts,
affordance_context,
image=sample.image_bytes,
detector=DETECTOR,
max_tool_rounds=int(max_tool_rounds),
auto_crop_top_k=0,
generation_kwargs={
"temperature": TEMPERATURE,
"max_tokens": MAX_NEW_TOKENS,
"max_new_tokens": MAX_NEW_TOKENS,
},
)
trace = loop_to_trace(loop)
goal_active = _goal_active(loop.response)
report = validate_operations(
loop.response.operations,
affordance_context,
scene_facts,
expected_non_empty_plan=bool(goal_active) if goal_active is not None else None,
goal_active=goal_active,
)
if not report.ok:
raise PlanRejected(report.messages, trace)
graph_plan = convert_operations_to_graph_plan(
loop.response.operations, affordance_context, scene_facts
)
graph_plan.build_mode = "lnsdl_agentic_tool_loop"
graph_plan.family_shortcut_used = False
graph_plan.builder_trace = {
"agentic_tool_loop": {
"stopped_reason": loop.stopped_reason,
"rounds": loop.rounds,
"tool_call_count": trace["executed_tool_call_count"],
"tool_names": trace["tool_names"],
"raw_op_count": len(loop.response.operations),
},
}
graph_plan = _assign_executors_to_graph(graph_plan, scene_facts)
micro_steps = dispatch_graph(graph_plan)
dispatcher_output = VIKI_L2_PROFILE.dispatcher_emitter.emit(
DispatcherPayload(
sample=sample,
initial_scene_facts=initial_scene_facts,
scene_facts=scene_facts,
graph_plan=graph_plan,
micro_steps=micro_steps,
)
)
result = PipelineResult(
sample=sample,
initial_scene_facts=initial_scene_facts,
scene_facts=scene_facts,
yolo_detections=None,
graph_plan=graph_plan,
selected_robot_types=collect_selected_robot_types(graph_plan),
micro_steps=micro_steps,
dispatcher_output=dispatcher_output,
)
return result, trace
def _micro_steps_table(micro_steps: list[Any]) -> list[dict[str, Any]]:
"""Render MicroStep(step: int, actions: dict[robot, [verb, target, ...]])."""
rows: list[dict[str, Any]] = []
for step in micro_steps:
step_no = int(getattr(step, "step", 0) or 0)
actions = getattr(step, "actions", None) or {}
rendered: dict[str, list[str]] = {}
for slot, action in actions.items():
if action in (None, "", []):
continue
if isinstance(action, (list, tuple)):
rendered[str(slot)] = [str(part) for part in action]
else:
rendered[str(slot)] = [str(action)]
rows.append({"step": step_no, "actions": rendered})
return rows
def _graph_summary(graph_plan: Any, result: PipelineResult) -> dict[str, Any]:
nodes = list(getattr(graph_plan, "nodes", []) or [])
node_rows = []
for node in nodes:
node_rows.append({
"id": str(getattr(node, "node_id", "") or ""),
"kind": str(getattr(node, "node_kind", "") or ""),
"goal": str(getattr(node, "semantic_goal", "") or ""),
"object": getattr(node, "object_name", None),
"destination": getattr(node, "destination", None),
"executor": getattr(node, "executor_slot", None),
"robot_type": getattr(node, "executor_robot_type", None),
"predecessors": list(getattr(node, "predecessors", []) or []),
})
return {
"node_count": len(nodes),
"nodes": node_rows,
"compiler_notes": list(getattr(graph_plan, "compiler_notes", []) or []),
"selected_robot_types": list(result.selected_robot_types or []),
}
def _sample_image_bytes(image: Any) -> bytes:
"""Normalize a Gradio image input to PNG bytes."""
from io import BytesIO
from PIL import Image
if image is None:
raise ValueError("Please provide a scene image.")
if isinstance(image, (bytes, bytearray)):
return bytes(image)
if isinstance(image, Path):
with Image.open(image) as img:
buf = BytesIO()
img.convert("RGB").save(buf, format="PNG")
return buf.getvalue()
if isinstance(image, str):
with Image.open(image) as img:
buf = BytesIO()
img.convert("RGB").save(buf, format="PNG")
return buf.getvalue()
# numpy array from gr.Image(type="numpy")
arr = image
with Image.fromarray(arr) as img:
buf = BytesIO()
img.convert("RGB").save(buf, format="PNG")
return buf.getvalue()
# ----------------------------------------------------------------------------
# Gradio handler
# ----------------------------------------------------------------------------
@spaces.GPU(duration=70)
def plan(
scene_image,
instruction: str,
robot_r1: str,
robot_r2: str,
robot_r3: str,
max_tool_rounds: int = MAX_TOOL_ROUNDS,
):
"""Plan a joint multi-robot task from a scene image and instruction.
Args:
scene_image: The scene image (overhead kitchen view).
instruction: Natural-language task instruction.
robot_r1: Robot type assigned to slot R1 (or "none").
robot_r2: Robot type assigned to slot R2 (or "none").
robot_r3: Robot type assigned to slot R3 (or "none").
max_tool_rounds: Maximum planner tool-call rounds.
Returns:
Tuple of (dispatcher output JSON, plan summary, tool trace JSON).
"""
started = time.perf_counter()
image_bytes = _sample_image_bytes(scene_image)
instruction = (instruction or "").strip()
if not instruction:
raise ValueError("Please provide a task instruction.")
inventory: dict[str, str | None] = {}
for slot, robot_type in (("R1", robot_r1), ("R2", robot_r2), ("R3", robot_r3)):
normalized = (robot_type or "").strip()
inventory[slot] = None if normalized in {"", "none", "None"} else normalized
sample = BenchmarkSample(
level="VIKI-L2",
split="demo",
sample_index=0,
task_id=None,
task_name=None,
instruction=instruction,
system_prompt="",
image_bytes=image_bytes,
robot_inventory=inventory,
)
try:
result, trace = _run_pipeline(sample, max_tool_rounds=max_tool_rounds)
rejected_messages: list[str] = []
except PlanRejected as rejection:
result = _empty_result(sample, rejection.trace.get("_scene_facts"))
trace = dict(rejection.trace)
rejected_messages = rejection.messages
elapsed = time.perf_counter() - started
trace["elapsed_seconds"] = round(elapsed, 2)
if rejected_messages:
trace["stopped_reason"] = "plan_rejected"
trace["rejection_messages"] = rejected_messages
print(f"[nsdl] plan rejected: {'; '.join(rejected_messages)}", flush=True)
else:
print(f"[nsdl] plan finished in {elapsed:.1f}s", flush=True)
dispatcher_json = json.dumps(
result.dispatcher_output, ensure_ascii=False, indent=2, default=_json_fallback
) if result.dispatcher_output is not None else (
json.dumps(
{
"status": "rejected",
"message": "The neuro-symbolic validator rejected the planner's operations: "
+ "; ".join(rejected_messages),
},
ensure_ascii=False,
indent=2,
)
if rejected_messages
else "null"
)
plan_summary = {
"elapsed_seconds": round(elapsed, 2),
"stopped_reason": trace.get("stopped_reason"),
"rejection_messages": trace.get("rejection_messages") or [],
"rounds": trace.get("rounds"),
"tool_names": trace.get("tool_names"),
"goal": (trace.get("final_response") or {}).get("goal"),
"assignments": (trace.get("final_response") or {}).get("assign"),
"operations": (trace.get("final_response") or {}).get("plan"),
"graph": _graph_summary(result.graph_plan, result),
"micro_steps": _micro_steps_table(result.micro_steps),
}
if rejected_messages:
plan_summary = dict(plan_summary)
plan_summary.pop("micro_steps", None)
summary_json = json.dumps(plan_summary, ensure_ascii=False, indent=2, default=_json_fallback)
trace_json = json.dumps(trace, ensure_ascii=False, indent=2, default=_json_fallback)
return dispatcher_json, summary_json, trace_json
# ----------------------------------------------------------------------------
# UI
# ----------------------------------------------------------------------------
EXAMPLES_DIR = Path(__file__).parent / "examples"
HEADER_MD = """
# NSDL: Neuro-Symbolic Division of Labor for Multi-Robot Task Planning
A fine-tuned **Qwen2.5-VL 7B** planner (`XinchengTan/nsdl-7b-rl-viki`) cooperates
with deterministic neuro-symbolic tools in an agentic loop: it emits a goal,
robot assignments and a plan sketch, may call `schedule` / `verify` / `detect` /
`expand` / `lookup` tools across rounds, and finally produces a validated joint
plan — lowered to a dependency graph, per-node robot executors, and dispatchable
micro-steps.
Upload a scene image, describe the task, pick the robots available, and press
**Plan task**.
""".strip()
FOOTER_MD = """
**Pipeline** (L-NSDL agentic tool loop, reference defaults: 3 tool rounds, 4096
max new tokens, greedy decoding; `ultralytics_yolo26` detector at conf 0.25 /
IoU 0.70 / max-det 64):
1. `scene_parser` / `scene_facts_refiner` build scene facts from the image.
2. The VLM planner runs a tool loop — `[GOAL] → [ASSIGN] → [PLAN_SKETCH] →
[TOOL_CALL] → [PLAN]` — where `schedule`, `verify`, `detect`, `expand` and
`lookup` execute deterministically between rounds.
3. Operations are validated (`validate_operations`) and lowered to a graph
plan, executors are assigned per node, and `dispatch_graph` expands them to
micro-steps.
Plans that fail symbolic validation are reported as `plan_rejected` with the
validator's messages — that is the neuro-symbolic checker doing its job, not a
crash.
Example images and instructions come from the
[locus-bench](https://huggingface.co/datasets/XinchengTan/locus-bench)
benchmark (CC-BY-4.0): in-distribution `test_id`, and out-of-distribution
`ood_s` / `ood_m` / `ood_x` splits.
""".strip()
NONE_OPTION = "none"
ROBOT_CHOICES = [NONE_OPTION] + ROBOT_TYPES
CUSTOM_CSS = """
.dark .gradio-container {background: #0b0f19;}
.gradio-container {max-width: 1280px !important; margin: 0 auto !important;}
"""
def build_ui() -> gr.Blocks:
with gr.Blocks(title="NSDL — Neuro-Symbolic Multi-Robot Task Planning") as demo:
gr.Markdown(HEADER_MD)
with gr.Row():
with gr.Column(scale=1):
scene_image = gr.Image(
label="Scene image",
type="numpy",
height=360,
)
instruction = gr.Textbox(
label="Task instruction",
placeholder="e.g. Relocate the bottle to the kitchen work area as instructed.",
lines=2,
)
with gr.Row():
robot_r1 = gr.Dropdown(
choices=ROBOT_CHOICES,
value="unitree_h1",
label="Robot R1",
)
robot_r2 = gr.Dropdown(
choices=ROBOT_CHOICES,
value=NONE_OPTION,
label="Robot R2",
)
robot_r3 = gr.Dropdown(
choices=ROBOT_CHOICES,
value=NONE_OPTION,
label="Robot R3",
)
plan_button = gr.Button("Plan task", variant="primary")
with gr.Accordion("Advanced", open=False):
max_tool_rounds = gr.Slider(
minimum=1,
maximum=6,
step=1,
value=MAX_TOOL_ROUNDS,
label="Max tool rounds",
info="How many planner-tool rounds the agentic loop may run.",
)
with gr.Column(scale=1):
dispatcher_output = gr.Code(
label="Dispatcher output",
language="json",
lines=18,
)
plan_summary = gr.Code(
label="Plan summary (goal · assignments · operations · graph · micro-steps)",
language="json",
lines=24,
)
with gr.Accordion("Agentic trace", open=False):
trace_output = gr.Code(
label="Tool-loop trace",
language="json",
lines=20,
)
gr.Markdown(FOOTER_MD)
gr.Examples(
examples=[
[
str(EXAMPLES_DIR / "test_id_00000.png"),
"Relocate the bottle to the kitchen work area as instructed.",
"unitree_h1",
NONE_OPTION,
NONE_OPTION,
3,
],
[
str(EXAMPLES_DIR / "ood_s_00000.png"),
"Make sure every fruit is on the table; fetch any fruit that isn't there yet.",
"unitree_h1",
NONE_OPTION,
NONE_OPTION,
3,
],
[
str(EXAMPLES_DIR / "ood_m_00000.png"),
"Serve the banana on the bowl—if it's not out on the counter, it's in the cabinet—and put the pumpkin away inside the cabinet as well.",
"unitree_h1",
NONE_OPTION,
NONE_OPTION,
3,
],
[
str(EXAMPLES_DIR / "ood_x_00000.png"),
"Get the banana onto the plate (check the cabinet if it isn't out), and stow the kettle in the cabinet while you're at it.",
"fetch",
"stompy",
NONE_OPTION,
6,
],
],
inputs=[scene_image, instruction, robot_r1, robot_r2, robot_r3, max_tool_rounds],
fn=plan,
outputs=[dispatcher_output, plan_summary, trace_output],
cache_examples=True,
cache_mode="lazy",
)
plan_button.click(
fn=plan,
inputs=[scene_image, instruction, robot_r1, robot_r2, robot_r3, max_tool_rounds],
outputs=[dispatcher_output, plan_summary, trace_output],
api_name="plan",
)
return demo
if __name__ == "__main__":
demo = build_ui()
demo.launch(
mcp_server=True,
theme=gr.themes.Citrus(),
css=CUSTOM_CSS,
)