Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- Dockerfile +89 -0
- README.md +60 -5
- __init__.py +16 -0
- client.py +106 -0
- implementation_plan.md +51 -0
- inference.py +256 -0
- models.py +38 -0
- openenv.yaml +7 -0
- openenv_rtl_debugger.egg-info/PKG-INFO +14 -0
- openenv_rtl_debugger.egg-info/SOURCES.txt +19 -0
- openenv_rtl_debugger.egg-info/dependency_links.txt +1 -0
- openenv_rtl_debugger.egg-info/entry_points.txt +2 -0
- openenv_rtl_debugger.egg-info/requires.txt +10 -0
- openenv_rtl_debugger.egg-info/top_level.txt +1 -0
- planning.md +36 -0
- pyproject.toml +50 -0
- server/__init__.py +11 -0
- server/app.py +84 -0
- server/rtl_debugger_environment.py +333 -0
- tasks/task2/context.md +1 -0
- tasks/task2/design_active.v +7 -0
- tasks/task2/design_buggy.v +7 -0
- tasks/task2/makefile +8 -0
- tasks/task2/result.json +49 -0
- tasks/task2/results.xml +6 -0
- tasks/task2/sim_build/cmds.f +1 -0
- tasks/task2/sim_build/sim.vvp +29 -0
- tasks/task2/test_xor_gate_simple.py +54 -0
- uv.lock +0 -0
- validate_submission.sh +184 -0
Dockerfile
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# Multi-stage build using openenv-base
|
| 8 |
+
# This Dockerfile is flexible and works for both:
|
| 9 |
+
# - In-repo environments (with local OpenEnv sources)
|
| 10 |
+
# - Standalone environments (with openenv from PyPI/Git)
|
| 11 |
+
# The build script (openenv build) handles context detection and sets appropriate build args.
|
| 12 |
+
|
| 13 |
+
ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
|
| 14 |
+
FROM ${BASE_IMAGE} AS builder
|
| 15 |
+
|
| 16 |
+
WORKDIR /app
|
| 17 |
+
|
| 18 |
+
# Ensure git, iverilog, and make are available
|
| 19 |
+
ARG DEBIAN_FRONTEND=noninteractive
|
| 20 |
+
RUN apt-get update && \
|
| 21 |
+
apt-get install -y --no-install-recommends git iverilog make && \
|
| 22 |
+
rm -rf /var/lib/apt/lists/*
|
| 23 |
+
|
| 24 |
+
# Build argument to control whether we're building standalone or in-repo
|
| 25 |
+
ARG BUILD_MODE=in-repo
|
| 26 |
+
ARG ENV_NAME=rtl_debugger
|
| 27 |
+
|
| 28 |
+
# Copy environment code (always at root of build context)
|
| 29 |
+
COPY . /app/env
|
| 30 |
+
|
| 31 |
+
# For in-repo builds, openenv is already vendored in the build context
|
| 32 |
+
# For standalone builds, openenv will be installed via pyproject.toml
|
| 33 |
+
WORKDIR /app/env
|
| 34 |
+
|
| 35 |
+
# Ensure uv is available (for local builds where base image lacks it)
|
| 36 |
+
RUN if ! command -v uv >/dev/null 2>&1; then \
|
| 37 |
+
curl -LsSf https://astral.sh/uv/install.sh | sh && \
|
| 38 |
+
mv /root/.local/bin/uv /usr/local/bin/uv && \
|
| 39 |
+
mv /root/.local/bin/uvx /usr/local/bin/uvx; \
|
| 40 |
+
fi
|
| 41 |
+
|
| 42 |
+
# Install dependencies using uv sync
|
| 43 |
+
# If uv.lock exists, use it; otherwise resolve on the fly
|
| 44 |
+
RUN --mount=type=cache,target=/root/.cache/uv \
|
| 45 |
+
if [ -f uv.lock ]; then \
|
| 46 |
+
uv sync --frozen --no-install-project --no-editable; \
|
| 47 |
+
else \
|
| 48 |
+
uv sync --no-install-project --no-editable; \
|
| 49 |
+
fi
|
| 50 |
+
|
| 51 |
+
RUN --mount=type=cache,target=/root/.cache/uv \
|
| 52 |
+
if [ -f uv.lock ]; then \
|
| 53 |
+
uv sync --frozen --no-editable; \
|
| 54 |
+
else \
|
| 55 |
+
uv sync --no-editable; \
|
| 56 |
+
fi
|
| 57 |
+
|
| 58 |
+
# Final runtime stage
|
| 59 |
+
FROM ${BASE_IMAGE}
|
| 60 |
+
|
| 61 |
+
# Install runtime dependencies (iverilog and make)
|
| 62 |
+
ARG DEBIAN_FRONTEND=noninteractive
|
| 63 |
+
RUN apt-get update && \
|
| 64 |
+
apt-get install -y --no-install-recommends iverilog make && \
|
| 65 |
+
rm -rf /var/lib/apt/lists/*
|
| 66 |
+
|
| 67 |
+
WORKDIR /app
|
| 68 |
+
|
| 69 |
+
# Copy the virtual environment from builder
|
| 70 |
+
COPY --from=builder /app/env/.venv /app/.venv
|
| 71 |
+
|
| 72 |
+
# Copy the environment code
|
| 73 |
+
COPY --from=builder /app/env /app/env
|
| 74 |
+
|
| 75 |
+
# Set PATH to use the virtual environment
|
| 76 |
+
ENV PATH="/app/.venv/bin:$PATH"
|
| 77 |
+
|
| 78 |
+
# Set PYTHONPATH so imports work correctly
|
| 79 |
+
ENV PYTHONPATH="/app/env:$PYTHONPATH"
|
| 80 |
+
|
| 81 |
+
ENV ENABLE_WEB_INTERFACE=true
|
| 82 |
+
|
| 83 |
+
# Health check
|
| 84 |
+
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
| 85 |
+
CMD curl -f http://localhost:8000/health || exit 1
|
| 86 |
+
|
| 87 |
+
# Run the FastAPI server
|
| 88 |
+
# The module path is constructed to work with the /app/env structure
|
| 89 |
+
CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]
|
README.md
CHANGED
|
@@ -1,10 +1,65 @@
|
|
| 1 |
---
|
| 2 |
-
title: RTL
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: RTL Debugger Environment
|
| 3 |
+
emoji: 🛠️
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: green
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
+
app_port: 8000
|
| 9 |
+
base_path: /web
|
| 10 |
+
tags:
|
| 11 |
+
- openenv
|
| 12 |
+
- verilog
|
| 13 |
+
- rl
|
| 14 |
+
- hardware-debugging
|
| 15 |
---
|
| 16 |
|
| 17 |
+
# RTL Debugger Environment
|
| 18 |
+
|
| 19 |
+
The **RTL Debugger** is a Reinforcement Learning environment designed for automated hardware design fixing. It enables LLM-based agents to iteratively debug Verilog code.
|
| 20 |
+
|
| 21 |
+
## Quick Start
|
| 22 |
+
|
| 23 |
+
### 1. Build the Environment
|
| 24 |
+
The environment runs in a Docker container to ensure all hardware tools (`iverilog`, `make`, `python-cocotb`) are correctly installed.
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
# Build the image locally
|
| 28 |
+
docker build -t rtl_debugger-env:latest .
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
### 2. Run the Server
|
| 32 |
+
```bash
|
| 33 |
+
# Start the environment server on port 8000
|
| 34 |
+
docker run -p 8000:8000 --rm rtl_debugger-env:latest
|
| 35 |
+
```
|
| 36 |
+
Access the web UI at [http://localhost:8000/web](http://localhost:8000/web).
|
| 37 |
+
|
| 38 |
+
### 3. Run the Inference Agent
|
| 39 |
+
We provide a reference inference script that uses LLM to play the environment:
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
# Install dependencies
|
| 43 |
+
uv sync
|
| 44 |
+
|
| 45 |
+
# Run the agent
|
| 46 |
+
uv run python inference.py
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
## Environment Details
|
| 50 |
+
|
| 51 |
+
### Action Model (`RtlDebuggerAction`)
|
| 52 |
+
Agents submit their corrected Verilog module:
|
| 53 |
+
- `fixed_code` (str): The full Verilog module source.
|
| 54 |
+
|
| 55 |
+
### Observation Model (`RtlDebuggerObservation`)
|
| 56 |
+
The environment returns detailed hardware-centric feedback:
|
| 57 |
+
- `design_code` (str): The initial (buggy) design for reference.
|
| 58 |
+
- `feedback` (str): Raw output from `iverilog` errors or `cocotb` testbench logs.
|
| 59 |
+
- `compiled` (bool): Whether the code successfully compiled.
|
| 60 |
+
- `passed_tests` (bool): Whether all functional testcases passed.
|
| 61 |
+
- `pass_rate` (float): Ratio of passed tests [0.0 - 1.0].
|
| 62 |
+
- `levenshtein_distance` (int): Number of lines modified compared to the previous step.
|
| 63 |
+
|
| 64 |
+
---
|
| 65 |
+
*Built with [OpenEnv](https://github.com/meta-pytorch/openenv-core)*.
|
__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""Rtl Debugger Environment."""
|
| 8 |
+
|
| 9 |
+
from .client import RtlDebuggerEnv
|
| 10 |
+
from .models import RtlDebuggerAction, RtlDebuggerObservation
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"RtlDebuggerAction",
|
| 14 |
+
"RtlDebuggerObservation",
|
| 15 |
+
"RtlDebuggerEnv",
|
| 16 |
+
]
|
client.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""Rtl Debugger Environment Client."""
|
| 8 |
+
|
| 9 |
+
from typing import Dict
|
| 10 |
+
|
| 11 |
+
from openenv.core import EnvClient
|
| 12 |
+
from openenv.core.client_types import StepResult
|
| 13 |
+
from openenv.core.env_server.types import State
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
from .models import RtlDebuggerAction, RtlDebuggerObservation
|
| 17 |
+
except ImportError:
|
| 18 |
+
from models import RtlDebuggerAction, RtlDebuggerObservation # type: ignore
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class RtlDebuggerEnv(
|
| 22 |
+
EnvClient[RtlDebuggerAction, RtlDebuggerObservation, State]
|
| 23 |
+
):
|
| 24 |
+
"""
|
| 25 |
+
Client for the Rtl Debugger Environment.
|
| 26 |
+
|
| 27 |
+
This client maintains a persistent WebSocket connection to the environment server,
|
| 28 |
+
enabling efficient multi-step interactions with lower latency.
|
| 29 |
+
Each client instance has its own dedicated environment session on the server.
|
| 30 |
+
|
| 31 |
+
Example:
|
| 32 |
+
>>> # Connect to a running server
|
| 33 |
+
>>> with RtlDebuggerEnv(base_url="http://localhost:8000") as client:
|
| 34 |
+
... result = client.reset()
|
| 35 |
+
... print(result.observation.echoed_message)
|
| 36 |
+
...
|
| 37 |
+
... result = client.step(RtlDebuggerAction(message="Hello!"))
|
| 38 |
+
... print(result.observation.echoed_message)
|
| 39 |
+
|
| 40 |
+
Example with Docker:
|
| 41 |
+
>>> # Automatically start container and connect
|
| 42 |
+
>>> client = RtlDebuggerEnv.from_docker_image("rtl_debugger-env:latest")
|
| 43 |
+
>>> try:
|
| 44 |
+
... result = client.reset()
|
| 45 |
+
... result = client.step(RtlDebuggerAction(message="Test"))
|
| 46 |
+
... finally:
|
| 47 |
+
... client.close()
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
def _step_payload(self, action: RtlDebuggerAction) -> Dict:
|
| 51 |
+
"""
|
| 52 |
+
Convert RtlDebuggerAction to JSON payload for step message.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
action: RtlDebuggerAction instance
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
Dictionary representation suitable for JSON encoding
|
| 59 |
+
"""
|
| 60 |
+
return {
|
| 61 |
+
"fixed_code": action.fixed_code,
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
def _parse_result(self, payload: Dict) -> StepResult[RtlDebuggerObservation]:
|
| 65 |
+
"""
|
| 66 |
+
Parse server response into StepResult[RtlDebuggerObservation].
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
payload: JSON response data from server
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
StepResult with RtlDebuggerObservation
|
| 73 |
+
"""
|
| 74 |
+
obs_data = payload.get("observation", {})
|
| 75 |
+
observation = RtlDebuggerObservation(
|
| 76 |
+
design_code=obs_data.get("design_code", ""),
|
| 77 |
+
feedback=obs_data.get("feedback", ""),
|
| 78 |
+
compiled=obs_data.get("compiled", False),
|
| 79 |
+
passed_tests=obs_data.get("passed_tests", False),
|
| 80 |
+
pass_rate=obs_data.get("pass_rate", 0.0),
|
| 81 |
+
simulation_time=obs_data.get("simulation_time", 0.0),
|
| 82 |
+
levenshtein_distance=obs_data.get("levenshtein_distance", 0),
|
| 83 |
+
reward=obs_data.get("reward", 0.0),
|
| 84 |
+
done=obs_data.get("done", False),
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
return StepResult(
|
| 88 |
+
observation=observation,
|
| 89 |
+
reward=payload.get("reward", observation.reward),
|
| 90 |
+
done=payload.get("done", observation.done),
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
def _parse_state(self, payload: Dict) -> State:
|
| 94 |
+
"""
|
| 95 |
+
Parse server response into State object.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
payload: JSON response from state request
|
| 99 |
+
|
| 100 |
+
Returns:
|
| 101 |
+
State object with episode_id and step_count
|
| 102 |
+
"""
|
| 103 |
+
return State(
|
| 104 |
+
episode_id=payload.get("episode_id"),
|
| 105 |
+
step_count=payload.get("step_count", 0),
|
| 106 |
+
)
|
implementation_plan.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Implement RTL Debugger Environment Evaluation using Cocotb
|
| 2 |
+
|
| 3 |
+
The goal is to update the RTL Debugger Environment to compute the new reward metrics based on Cocotb `make` results, parse [result.json](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/result.json), compute the final Grader Score, and update the Observation model.
|
| 4 |
+
|
| 5 |
+
## Proposed Changes
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
### Shared Models
|
| 10 |
+
Update the observation and action models to reflect the new metrics.
|
| 11 |
+
|
| 12 |
+
#### [MODIFY] models.py
|
| 13 |
+
- Ensure `fixed_code` is consistently used everywhere per your request. [RtlDebuggerAction](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/models.py#17-21) keeps `fixed_code: str`.
|
| 14 |
+
- Add new metrics to [RtlDebuggerObservation](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/models.py#23-32):
|
| 15 |
+
- `pass_rate: float = Field(default=0.0)`
|
| 16 |
+
- `simulation_time: float = Field(default=0.0)`
|
| 17 |
+
- `levenshtein_distance: int = Field(default=0)`
|
| 18 |
+
- Modify `reward: float` field description.
|
| 19 |
+
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
### Core Environment
|
| 23 |
+
Revamp the simulation logic to utilize `make` and parse the cocotb output.
|
| 24 |
+
|
| 25 |
+
#### [MODIFY] server/rtl_debugger_environment.py
|
| 26 |
+
- Fix references of `action.code` to `action.fixed_code`.
|
| 27 |
+
- Add a dedicated `<grader>` function that computes the final score normalized between 0 and 1. `Score_final = PassRate` (LintWarnings subtracted if implemented later). It will be invoked at the end of the RL sequence.
|
| 28 |
+
- Overwrite [step()](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/server/rtl_debugger_environment.py#109-167) method:
|
| 29 |
+
1. Write `action.fixed_code` to [design.v](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/design.v) inside a `temp_dir`.
|
| 30 |
+
2. Copy all files from `task_dir` (like [makefile](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/makefile) and Python tests) to `temp_dir`.
|
| 31 |
+
3. Calculate Levenshtein line distance between `self._design_code` and `action.fixed_code` using Python's built-in `difflib.ndiff` (no external dependency needed).
|
| 32 |
+
4. Explicitly test compilation using `iverilog -t null design.v`. If this fails, the process stops here, returning an observation indicating compilation failure and a negative reward.
|
| 33 |
+
5. If compilation passes, run `make` via `subprocess.run()`.
|
| 34 |
+
6. Read [result.json](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/result.json) if it exists. Extract `simulation_time` which is now populated directly by the testbench.
|
| 35 |
+
7. Calculate `pass_rate = num_passed / num_tests`, and assign it to the observation.
|
| 36 |
+
|
| 37 |
+
---
|
| 38 |
+
|
| 39 |
+
### Task Files
|
| 40 |
+
We need to update the Task 2 testing script so it directly outputs simulation time.
|
| 41 |
+
|
| 42 |
+
#### [MODIFY] tasks/task2/test_xor_gate_simple.py
|
| 43 |
+
- In the [test_xor_gate_simple.py](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/test_xor_gate_simple.py) testbench, inject simulation time into [result.json](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/result.json) automatically using `cocotb.utils.get_sim_time('ns')` at the end of the run.
|
| 44 |
+
|
| 45 |
+
---
|
| 46 |
+
|
| 47 |
+
## Verification Plan
|
| 48 |
+
|
| 49 |
+
### Automated Tests
|
| 50 |
+
1. I'll verify the grader function by unit testing it manually within [app.py](file:///c:/Users/npkas/Agentic-RL/rtl_debugger/server/app.py) or a scratch script.
|
| 51 |
+
2. Ensure that it reports partial pass rates, proper simulation times, and levenstein line diff counts.
|
inference.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Inference Script — RTL Debugger Environment
|
| 3 |
+
============================================
|
| 4 |
+
MANDATORY
|
| 5 |
+
- Before submitting, ensure the following variables are set in your environment:
|
| 6 |
+
API_BASE_URL The API endpoint for the LLM (e.g. https://router.huggingface.co/v1)
|
| 7 |
+
MODEL_NAME The model identifier to use for inference.
|
| 8 |
+
HF_TOKEN Your Hugging Face / API key.
|
| 9 |
+
|
| 10 |
+
- The inference script must be named `inference.py` and placed in the root of the project.
|
| 11 |
+
- Participants must use the OpenAI client for all LLM calls using the above variables.
|
| 12 |
+
|
| 13 |
+
Workflow:
|
| 14 |
+
1. env.reset() returns the initial feedback (environment ready message).
|
| 15 |
+
2. Each step, the LLM receives:
|
| 16 |
+
- The original buggy design.v (for reference)
|
| 17 |
+
- The full conversation history of (code, feedback) pairs
|
| 18 |
+
- The latest feedback (compiler errors or simulation output)
|
| 19 |
+
3. The LLM must reply with a complete Verilog module inside a ```verilog ... ``` block.
|
| 20 |
+
4. The extracted code is submitted as an action; the environment compiles and runs it.
|
| 21 |
+
5. Episode ends when all tests pass (done=True) or MAX_STEPS is reached.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import os
|
| 25 |
+
import re
|
| 26 |
+
import textwrap
|
| 27 |
+
import time
|
| 28 |
+
from typing import List, Tuple
|
| 29 |
+
|
| 30 |
+
# Load .env from this file's directory or any parent (picks up repo-root .env)
|
| 31 |
+
try:
|
| 32 |
+
from dotenv import load_dotenv, find_dotenv
|
| 33 |
+
load_dotenv(find_dotenv(usecwd=False)) # walks up from __file__ location
|
| 34 |
+
except ImportError:
|
| 35 |
+
pass # dotenv not installed; rely on environment variables being set manually
|
| 36 |
+
|
| 37 |
+
from openai import OpenAI
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
from .client import RtlDebuggerEnv
|
| 41 |
+
from .models import RtlDebuggerAction
|
| 42 |
+
except ImportError:
|
| 43 |
+
from client import RtlDebuggerEnv # type: ignore
|
| 44 |
+
from models import RtlDebuggerAction # type: ignore
|
| 45 |
+
|
| 46 |
+
# --- Configuration -------------------------------------------------------------
|
| 47 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 48 |
+
|
| 49 |
+
if GEMINI_API_KEY:
|
| 50 |
+
# Set defaults for Gemini (which uses an OpenAI-compatible endpoint)
|
| 51 |
+
API_BASE_URL = os.getenv("API_BASE_URL") or "https://generativelanguage.googleapis.com/v1beta/openai/"
|
| 52 |
+
API_KEY = GEMINI_API_KEY
|
| 53 |
+
MODEL_NAME = os.getenv("MODEL_NAME") or "gemini-2.5-flash"
|
| 54 |
+
else:
|
| 55 |
+
# Fall back to Hugging Face router
|
| 56 |
+
API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"
|
| 57 |
+
API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
|
| 58 |
+
MODEL_NAME = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-72B-Instruct"
|
| 59 |
+
|
| 60 |
+
TASK_NAME = os.getenv("RTL_DEBUGGER_TASK_NAME", "unknown-task")
|
| 61 |
+
IMAGE_NAME = os.getenv("IMAGE_NAME")
|
| 62 |
+
|
| 63 |
+
MAX_STEPS = 8
|
| 64 |
+
TEMPERATURE = 0.2
|
| 65 |
+
MAX_TOKENS = 1024
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# --- Prompts -------------------------------------------------------------------
|
| 71 |
+
SYSTEM_PROMPT = textwrap.dedent(
|
| 72 |
+
"""
|
| 73 |
+
You are an expert Verilog hardware designer and debugger.
|
| 74 |
+
Your task is to fix a buggy Verilog design module so that it passes all testcases.
|
| 75 |
+
|
| 76 |
+
Rules:
|
| 77 |
+
- Reply with ONLY the corrected Verilog module, enclosed in a ```verilog ... ``` code block.
|
| 78 |
+
- Do NOT include any explanation or commentary outside the code block.
|
| 79 |
+
- Your code must compile with iverilog and pass all $display-based PASS/FAIL checks.
|
| 80 |
+
- If there is a compilation error, carefully read the error and fix the syntax first.
|
| 81 |
+
- If tests fail, read the simulation output and fix the logic.
|
| 82 |
+
"""
|
| 83 |
+
).strip()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _load_file(path: str) -> str:
|
| 87 |
+
"""Read a file, returning its contents or a placeholder if missing."""
|
| 88 |
+
try:
|
| 89 |
+
with open(path, "r") as f:
|
| 90 |
+
return f.read()
|
| 91 |
+
except FileNotFoundError:
|
| 92 |
+
return f"(file not found: {path})"
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _build_user_prompt(
|
| 96 |
+
step: int,
|
| 97 |
+
initial_design: str,
|
| 98 |
+
history: List[Tuple[str, str]],
|
| 99 |
+
latest_feedback: str,
|
| 100 |
+
) -> str:
|
| 101 |
+
"""
|
| 102 |
+
Build the user prompt for the current step.
|
| 103 |
+
|
| 104 |
+
Args:
|
| 105 |
+
step: Current step number (1-indexed).
|
| 106 |
+
initial_design: The original buggy Verilog design.
|
| 107 |
+
history: List of (code_submitted, feedback_received) from previous steps.
|
| 108 |
+
latest_feedback: The most recent feedback from the environment.
|
| 109 |
+
"""
|
| 110 |
+
history_section = ""
|
| 111 |
+
if history:
|
| 112 |
+
history_lines = []
|
| 113 |
+
for i, (code, feedback) in enumerate(history[-4:], start=1):
|
| 114 |
+
history_lines.append(
|
| 115 |
+
f"--- Attempt {i} ---\n"
|
| 116 |
+
f"```verilog\n{code.strip()}\n```\n"
|
| 117 |
+
f"Feedback:\n{feedback.strip()}"
|
| 118 |
+
)
|
| 119 |
+
history_section = "\n\nPrevious attempts:\n" + "\n\n".join(history_lines)
|
| 120 |
+
|
| 121 |
+
return textwrap.dedent(
|
| 122 |
+
f"""
|
| 123 |
+
Step {step} — Fix the Verilog design module.
|
| 124 |
+
|
| 125 |
+
--- Original (buggy) design ---
|
| 126 |
+
```verilog
|
| 127 |
+
{initial_design.strip()}
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
+
{history_section}
|
| 131 |
+
|
| 132 |
+
--- Latest simulator feedback ---
|
| 133 |
+
{latest_feedback.strip() or "(no output)"}
|
| 134 |
+
|
| 135 |
+
Reply with the corrected design module in a ```verilog ... ``` block.
|
| 136 |
+
"""
|
| 137 |
+
).strip()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _extract_verilog(response_text: str) -> str:
|
| 141 |
+
"""
|
| 142 |
+
Extract the Verilog code block from the LLM response.
|
| 143 |
+
|
| 144 |
+
Falls back to returning the entire response if no fenced block is found.
|
| 145 |
+
"""
|
| 146 |
+
match = re.search(r"```verilog\s*(.*?)```", response_text, re.DOTALL | re.IGNORECASE)
|
| 147 |
+
if match:
|
| 148 |
+
return match.group(1).strip()
|
| 149 |
+
|
| 150 |
+
# Try a plain ``` block
|
| 151 |
+
match = re.search(r"```\s*(.*?)```", response_text, re.DOTALL)
|
| 152 |
+
if match:
|
| 153 |
+
return match.group(1).strip()
|
| 154 |
+
|
| 155 |
+
# Last resort: return the whole response
|
| 156 |
+
return response_text.strip()
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _get_llm_response(llm: OpenAI, messages: List[dict], max_retries: int = 4) -> str:
|
| 160 |
+
"""Gets LLM response with basic retry logic for rate limits and temporary failures."""
|
| 161 |
+
for attempt in range(max_retries):
|
| 162 |
+
try:
|
| 163 |
+
completion = llm.chat.completions.create(
|
| 164 |
+
model=MODEL_NAME,
|
| 165 |
+
messages=messages,
|
| 166 |
+
temperature=TEMPERATURE,
|
| 167 |
+
max_tokens=MAX_TOKENS,
|
| 168 |
+
stream=False,
|
| 169 |
+
)
|
| 170 |
+
return completion.choices[0].message.content or ""
|
| 171 |
+
except Exception as exc:
|
| 172 |
+
# Check for rate limit or retryable errors
|
| 173 |
+
err_msg = str(exc).lower()
|
| 174 |
+
if "rate limit" in err_msg or "too many requests" in err_msg or "temporary" in err_msg or attempt < max_retries - 1:
|
| 175 |
+
wait_time = (2 ** attempt) * 2 # Exponential backoff: 2, 4, 8, 16...
|
| 176 |
+
print(f"[Retry] Attempt {attempt + 1} failed: {exc}. Retrying in {wait_time}s...")
|
| 177 |
+
time.sleep(wait_time)
|
| 178 |
+
else:
|
| 179 |
+
raise exc
|
| 180 |
+
return ""
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
SERVER_URL = os.getenv("RTL_SERVER_URL", "http://localhost:8000")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def main() -> None:
|
| 187 |
+
llm = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
|
| 188 |
+
|
| 189 |
+
history: List[Tuple[str, str]] = [] # (code, feedback) pairs
|
| 190 |
+
rewards: List[float] = []
|
| 191 |
+
success = False
|
| 192 |
+
num_steps = 0
|
| 193 |
+
|
| 194 |
+
with RtlDebuggerEnv(base_url=SERVER_URL).sync() as env:
|
| 195 |
+
# Pass TASK_NAME if specified to select a specific task
|
| 196 |
+
reset_options = {"TASK_NAME": TASK_NAME} if TASK_NAME and TASK_NAME != "unknown-task" else None
|
| 197 |
+
result = env.reset(options=reset_options)
|
| 198 |
+
obs = result.observation
|
| 199 |
+
initial_design = obs.design_code
|
| 200 |
+
latest_feedback = obs.feedback
|
| 201 |
+
|
| 202 |
+
print(f"[Reset] {latest_feedback}")
|
| 203 |
+
if not initial_design:
|
| 204 |
+
print("[End] success=False steps=0 rewards=[] score=0.0 (no design code received)")
|
| 205 |
+
return
|
| 206 |
+
|
| 207 |
+
for step in range(1, MAX_STEPS + 1):
|
| 208 |
+
if result.done:
|
| 209 |
+
break
|
| 210 |
+
|
| 211 |
+
user_prompt = _build_user_prompt(
|
| 212 |
+
step=step,
|
| 213 |
+
initial_design=initial_design,
|
| 214 |
+
history=history,
|
| 215 |
+
latest_feedback=latest_feedback,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
messages = [
|
| 219 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 220 |
+
{"role": "user", "content": user_prompt},
|
| 221 |
+
]
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
response_text = _get_llm_response(llm, messages)
|
| 225 |
+
except Exception as exc:
|
| 226 |
+
print(f"[Step] step={step} action=\"<llm_error>\" reward=0.0 done=False # {exc}")
|
| 227 |
+
break
|
| 228 |
+
|
| 229 |
+
code = _extract_verilog(response_text)
|
| 230 |
+
action_preview = code.replace("\n", "\\n")[:120]
|
| 231 |
+
|
| 232 |
+
result = env.step(RtlDebuggerAction(fixed_code=code))
|
| 233 |
+
obs = result.observation
|
| 234 |
+
num_steps = step
|
| 235 |
+
|
| 236 |
+
latest_feedback = obs.feedback
|
| 237 |
+
rewards.append(result.reward)
|
| 238 |
+
history.append((code, obs.feedback))
|
| 239 |
+
success = result.done
|
| 240 |
+
|
| 241 |
+
print(f"[Step] step={step} action=\"{action_preview}...\" reward={result.reward:+.3f} done={result.done}")
|
| 242 |
+
print(f" compiled={obs.compiled} | tests={obs.passed_tests} | pass_rate={obs.pass_rate:.2f} | sim_time={obs.simulation_time:.1f}ns | lev_dist={obs.levenshtein_distance}")
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
# Call the grader for the final score
|
| 246 |
+
try:
|
| 247 |
+
score = env.grade()
|
| 248 |
+
except Exception:
|
| 249 |
+
score = 0.0
|
| 250 |
+
|
| 251 |
+
print(f"[End] success={success} steps={num_steps} rewards={[round(r, 3) for r in rewards]} score={score:.3f}")
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
if __name__ == "__main__":
|
| 255 |
+
main()
|
| 256 |
+
|
models.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
Data models for the Rtl Debugger Environment.
|
| 9 |
+
|
| 10 |
+
The rtl_debugger environment is a simple test environment that echoes back messages.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from openenv.core.env_server.types import Action, Observation
|
| 14 |
+
from pydantic import Field
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class RtlDebuggerAction(Action):
|
| 18 |
+
"""Action for the Rtl Debugger environment - submitting Verilog code."""
|
| 19 |
+
|
| 20 |
+
fixed_code: str = Field(
|
| 21 |
+
...,
|
| 22 |
+
title="Verilog Code Submission",
|
| 23 |
+
description="Paste your corrected Verilog design here. Ensure the module name and ports match the original.",
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RtlDebuggerObservation(Observation):
|
| 28 |
+
"""Observation from the Rtl Debugger environment - compilation and simulation results."""
|
| 29 |
+
|
| 30 |
+
design_code: str = Field(default="", description="The current buggy design code to fix")
|
| 31 |
+
feedback: str = Field(default="", description="Feedback from compilation or simulation")
|
| 32 |
+
compiled: bool = Field(default=False, description="Whether the code compiled successfully")
|
| 33 |
+
passed_tests: bool = Field(default=False, description="Whether all test cases passed")
|
| 34 |
+
pass_rate: float = Field(default=0.0, description="Functional Pass Rate (0.0 to 1.0)")
|
| 35 |
+
simulation_time: float = Field(default=0.0, description="Simulation time mapped from cocotb results")
|
| 36 |
+
levenshtein_distance: int = Field(default=0, description="Number of lines changed")
|
| 37 |
+
reward: float = Field(default=0.0, description="Final Reward / Score computed by the Grader")
|
| 38 |
+
done: bool = Field(default=False, description="Whether the episode is done")
|
openenv.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
spec_version: 1
|
| 2 |
+
name: rtl_debugger
|
| 3 |
+
type: space
|
| 4 |
+
runtime: fastapi
|
| 5 |
+
app: server.app:app
|
| 6 |
+
port: 8000
|
| 7 |
+
|
openenv_rtl_debugger.egg-info/PKG-INFO
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: openenv-rtl_debugger
|
| 3 |
+
Version: 0.1.0
|
| 4 |
+
Summary: Rtl Debugger environment for OpenEnv
|
| 5 |
+
Requires-Python: >=3.10
|
| 6 |
+
Requires-Dist: cocotb>=2.0.1
|
| 7 |
+
Requires-Dist: fastapi>=0.135.2
|
| 8 |
+
Requires-Dist: openai>=2.30.0
|
| 9 |
+
Requires-Dist: openenv-core[core]>=0.2.3
|
| 10 |
+
Requires-Dist: pydantic>=2.12.5
|
| 11 |
+
Requires-Dist: uvicorn>=0.42.0
|
| 12 |
+
Provides-Extra: dev
|
| 13 |
+
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
| 14 |
+
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
|
openenv_rtl_debugger.egg-info/SOURCES.txt
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
README.md
|
| 2 |
+
__init__.py
|
| 3 |
+
client.py
|
| 4 |
+
inference.py
|
| 5 |
+
models.py
|
| 6 |
+
pyproject.toml
|
| 7 |
+
./__init__.py
|
| 8 |
+
./client.py
|
| 9 |
+
./inference.py
|
| 10 |
+
./models.py
|
| 11 |
+
openenv_rtl_debugger.egg-info/PKG-INFO
|
| 12 |
+
openenv_rtl_debugger.egg-info/SOURCES.txt
|
| 13 |
+
openenv_rtl_debugger.egg-info/dependency_links.txt
|
| 14 |
+
openenv_rtl_debugger.egg-info/entry_points.txt
|
| 15 |
+
openenv_rtl_debugger.egg-info/requires.txt
|
| 16 |
+
openenv_rtl_debugger.egg-info/top_level.txt
|
| 17 |
+
server/__init__.py
|
| 18 |
+
server/app.py
|
| 19 |
+
server/rtl_debugger_environment.py
|
openenv_rtl_debugger.egg-info/dependency_links.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
openenv_rtl_debugger.egg-info/entry_points.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
server = rtl_debugger.server.app:main
|
openenv_rtl_debugger.egg-info/requires.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cocotb>=2.0.1
|
| 2 |
+
fastapi>=0.135.2
|
| 3 |
+
openai>=2.30.0
|
| 4 |
+
openenv-core[core]>=0.2.3
|
| 5 |
+
pydantic>=2.12.5
|
| 6 |
+
uvicorn>=0.42.0
|
| 7 |
+
|
| 8 |
+
[dev]
|
| 9 |
+
pytest>=8.0.0
|
| 10 |
+
pytest-cov>=4.0.0
|
openenv_rtl_debugger.egg-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
rtl_debugger
|
planning.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Environment:
|
| 2 |
+
The tasks involve debugging errors in verilog code.
|
| 3 |
+
First compile the task using iverilog
|
| 4 |
+
If compiled successfully then run make to run the cocotb testbench. Parse the output of the result.json produced to get the below 4 factors of reward rubric.
|
| 5 |
+
|
| 6 |
+
Check tasks/task2 for correct reference
|
| 7 |
+
|
| 8 |
+
## Reward rubric:
|
| 9 |
+
Compile Status: Did iverilog crash? (Binary: 0 or 1).
|
| 10 |
+
Pass Percentage: num_passed / num_tests from your JSON.
|
| 11 |
+
Simulation Time: How long did it run before an assertion hit?
|
| 12 |
+
Levenstein Distance (penalty): How many lines of code did the agent change?
|
| 13 |
+
|
| 14 |
+
We need a meaningful reward with partial progress signals
|
| 15 |
+
Later also look at giving partial progress based on waveform/timing correctness. We can consider: per-cycle correctness, transition correctness, stability award etc.
|
| 16 |
+
|
| 17 |
+
## The Grader (The "Judge")
|
| 18 |
+
The Grader is a binary or tiered evaluator that only cares about the Destination. It should be based on a passing the testbench. It's score varies between 0 and 1.
|
| 19 |
+
Metric 1: Functional Pass Rate. $\frac{Tests_{passed}}{Tests_{total}}$.
|
| 20 |
+
Metric 2: Structural Integrity. A Boolean check: Did the agent keep the same module name and ports? (Using a regex or a simple AST check).
|
| 21 |
+
Metric 3: Lint Cleanliness. Does it pass verilator --lint-only without warnings?The Grader's Formula:$$Score_{final} = (PassRate \times 100) - (LintWarnings \times 2)$$(If the code doesn't compile, the score is 0, period.)
|
| 22 |
+
(Metric 3 tbd later since i need to setup verilator first)
|
| 23 |
+
|
| 24 |
+
The grader should run instantly after the agent gives its final output.
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# Inference.py
|
| 28 |
+
Simply calls an LLM used as a baseline to test the env.
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
to do:
|
| 32 |
+
more difficult tasks -> sequential, waveform analysis based, dut and tb both can be wrong so more probing required etc.
|
| 33 |
+
improve the partial progress reward signals
|
| 34 |
+
complete the grader
|
| 35 |
+
make it submission ready
|
| 36 |
+
|
pyproject.toml
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
[build-system]
|
| 8 |
+
requires = ["setuptools>=45", "wheel"]
|
| 9 |
+
build-backend = "setuptools.build_meta"
|
| 10 |
+
|
| 11 |
+
[project]
|
| 12 |
+
name = "openenv-rtl_debugger"
|
| 13 |
+
version = "0.1.0"
|
| 14 |
+
description = "Rtl Debugger environment for OpenEnv"
|
| 15 |
+
requires-python = ">=3.10"
|
| 16 |
+
dependencies = [
|
| 17 |
+
"cocotb>=2.0.1",
|
| 18 |
+
# Core OpenEnv runtime (provides FastAPI server + HTTP client types)
|
| 19 |
+
# install from github
|
| 20 |
+
# "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git",
|
| 21 |
+
# Environment-specific dependencies
|
| 22 |
+
# Add all dependencies needed for your environment here
|
| 23 |
+
# Examples:
|
| 24 |
+
# "numpy>=1.19.0",
|
| 25 |
+
# "torch>=2.0.0",
|
| 26 |
+
# "gymnasium>=0.29.0",
|
| 27 |
+
# "openspiel>=1.0.0",
|
| 28 |
+
# "smolagents>=1.22.0,<2",
|
| 29 |
+
"fastapi>=0.135.2",
|
| 30 |
+
"openai>=2.30.0",
|
| 31 |
+
"openenv-core[core]>=0.2.3",
|
| 32 |
+
"pydantic>=2.12.5",
|
| 33 |
+
"uvicorn>=0.42.0",
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
[project.optional-dependencies]
|
| 37 |
+
dev = [
|
| 38 |
+
"pytest>=8.0.0",
|
| 39 |
+
"pytest-cov>=4.0.0",
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
[project.scripts]
|
| 43 |
+
# Server entry point - enables running via: uv run --project . server
|
| 44 |
+
# or: python -m rtl_debugger.server.app
|
| 45 |
+
server = "rtl_debugger.server.app:main"
|
| 46 |
+
|
| 47 |
+
[tool.setuptools]
|
| 48 |
+
include-package-data = true
|
| 49 |
+
packages = ["rtl_debugger", "rtl_debugger.server"]
|
| 50 |
+
package-dir = { "rtl_debugger" = ".", "rtl_debugger.server" = "server" }
|
server/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""Rtl Debugger environment server components."""
|
| 8 |
+
|
| 9 |
+
from .rtl_debugger_environment import RtlDebuggerEnvironment
|
| 10 |
+
|
| 11 |
+
__all__ = ["RtlDebuggerEnvironment"]
|
server/app.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
FastAPI application for the Rtl Debugger Environment.
|
| 9 |
+
|
| 10 |
+
This module creates an HTTP server that exposes the RtlDebuggerEnvironment
|
| 11 |
+
over HTTP and WebSocket endpoints, compatible with EnvClient.
|
| 12 |
+
|
| 13 |
+
Endpoints:
|
| 14 |
+
- POST /reset: Reset the environment
|
| 15 |
+
- POST /step: Execute an action
|
| 16 |
+
- GET /state: Get current environment state
|
| 17 |
+
- GET /schema: Get action/observation schemas
|
| 18 |
+
- WS /ws: WebSocket endpoint for persistent sessions
|
| 19 |
+
|
| 20 |
+
Usage:
|
| 21 |
+
# Development (with auto-reload):
|
| 22 |
+
uvicorn server.app:app --reload --host 0.0.0.0 --port 8000
|
| 23 |
+
|
| 24 |
+
# Production:
|
| 25 |
+
uvicorn server.app:app --host 0.0.0.0 --port 8000 --workers 4
|
| 26 |
+
|
| 27 |
+
# Or run directly:
|
| 28 |
+
python -m server.app
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
from openenv.core.env_server.http_server import create_app
|
| 33 |
+
except Exception as e: # pragma: no cover
|
| 34 |
+
raise ImportError(
|
| 35 |
+
"openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
|
| 36 |
+
) from e
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
from models import RtlDebuggerAction, RtlDebuggerObservation
|
| 40 |
+
from rtl_debugger_environment import RtlDebuggerEnvironment
|
| 41 |
+
except ModuleNotFoundError:
|
| 42 |
+
from models import RtlDebuggerAction, RtlDebuggerObservation
|
| 43 |
+
from server.rtl_debugger_environment import RtlDebuggerEnvironment
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# Create the app with web interface and README integration
|
| 47 |
+
app = create_app(
|
| 48 |
+
RtlDebuggerEnvironment,
|
| 49 |
+
RtlDebuggerAction,
|
| 50 |
+
RtlDebuggerObservation,
|
| 51 |
+
env_name="rtl_debugger",
|
| 52 |
+
max_concurrent_envs=1, # increase this number to allow more concurrent WebSocket sessions
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def main(host: str = "0.0.0.0", port: int = 8000):
|
| 57 |
+
"""
|
| 58 |
+
Entry point for direct execution via uv run or python -m.
|
| 59 |
+
|
| 60 |
+
This function enables running the server without Docker:
|
| 61 |
+
uv run --project . server
|
| 62 |
+
uv run --project . server --port 8001
|
| 63 |
+
python -m rtl_debugger.server.app
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
host: Host address to bind to (default: "0.0.0.0")
|
| 67 |
+
port: Port number to listen on (default: 8000)
|
| 68 |
+
|
| 69 |
+
For production deployments, consider using uvicorn directly with
|
| 70 |
+
multiple workers:
|
| 71 |
+
uvicorn rtl_debugger.server.app:app --workers 4
|
| 72 |
+
"""
|
| 73 |
+
import uvicorn
|
| 74 |
+
|
| 75 |
+
uvicorn.run(app, host=host, port=port)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
import argparse
|
| 80 |
+
|
| 81 |
+
parser = argparse.ArgumentParser()
|
| 82 |
+
parser.add_argument("--port", type=int, default=8000)
|
| 83 |
+
args = parser.parse_args()
|
| 84 |
+
main(port=args.port)
|
server/rtl_debugger_environment.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
Rtl Debugger Environment Implementation.
|
| 9 |
+
|
| 10 |
+
On reset(), a random task is loaded from the tasks/ directory.
|
| 11 |
+
Each task folder must contain:
|
| 12 |
+
design_buggy.v - the immutable original buggy module shown to the agent
|
| 13 |
+
makefile - the cocotb makefile (must reference design_active.v)
|
| 14 |
+
test_*.py - the cocotb testbench(es) that produce result.json
|
| 15 |
+
|
| 16 |
+
design_active.v is created on reset() as a mutable working copy of design_buggy.v.
|
| 17 |
+
The agent overwrites design_active.v each step, so it iterates on its own previous fix.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import difflib
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import random
|
| 24 |
+
import re
|
| 25 |
+
import shutil
|
| 26 |
+
import subprocess
|
| 27 |
+
import traceback
|
| 28 |
+
from uuid import uuid4
|
| 29 |
+
|
| 30 |
+
from openenv.core.env_server.interfaces import Environment
|
| 31 |
+
from openenv.core.env_server.types import State
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
from ..models import RtlDebuggerAction, RtlDebuggerObservation
|
| 35 |
+
except ImportError:
|
| 36 |
+
from models import RtlDebuggerAction, RtlDebuggerObservation
|
| 37 |
+
|
| 38 |
+
# Tasks directory is always at <package_root>/tasks/
|
| 39 |
+
_TASKS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "tasks"))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _list_tasks() -> list[str]:
|
| 43 |
+
"""Return sorted list of task directory paths found under _TASKS_DIR.
|
| 44 |
+
|
| 45 |
+
A valid task must contain design_buggy.v and a makefile.
|
| 46 |
+
"""
|
| 47 |
+
if not os.path.isdir(_TASKS_DIR):
|
| 48 |
+
return []
|
| 49 |
+
return sorted(
|
| 50 |
+
os.path.join(_TASKS_DIR, name)
|
| 51 |
+
for name in os.listdir(_TASKS_DIR)
|
| 52 |
+
if os.path.isdir(os.path.join(_TASKS_DIR, name))
|
| 53 |
+
and os.path.exists(os.path.join(_TASKS_DIR, name, "design_buggy.v"))
|
| 54 |
+
and os.path.exists(os.path.join(_TASKS_DIR, name, "makefile"))
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _read(path: str) -> str:
|
| 59 |
+
with open(path, "r") as f:
|
| 60 |
+
return f.read()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _levenshtein_line_distance(original: str, modified: str) -> int:
|
| 64 |
+
"""
|
| 65 |
+
Compute the number of changed lines between two strings using difflib.
|
| 66 |
+
Counts lines that are added or removed (not unchanged context lines).
|
| 67 |
+
"""
|
| 68 |
+
orig_lines = original.splitlines(keepends=True)
|
| 69 |
+
mod_lines = modified.splitlines(keepends=True)
|
| 70 |
+
diffs = list(difflib.ndiff(orig_lines, mod_lines))
|
| 71 |
+
changed = sum(1 for d in diffs if d.startswith("+ ") or d.startswith("- "))
|
| 72 |
+
return changed
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def grader(result_json: dict, module_name_original: str, submitted_code: str) -> float:
|
| 76 |
+
"""
|
| 77 |
+
The Grader — evaluates the agent's final output.
|
| 78 |
+
|
| 79 |
+
Metric 1: Functional Pass Rate = num_passed / num_tests (0.0 – 1.0)
|
| 80 |
+
Metric 2: Structural Integrity = module name preserved (Boolean) — TBD
|
| 81 |
+
Metric 3: Lint Cleanliness = TBD (verilator not yet set up)
|
| 82 |
+
|
| 83 |
+
Formula (current):
|
| 84 |
+
Score_final = PassRate (in [0.0, 1.0])
|
| 85 |
+
|
| 86 |
+
Returns a float in [0.0, 1.0].
|
| 87 |
+
"""
|
| 88 |
+
num_tests = result_json.get("num_tests", 1)
|
| 89 |
+
num_passed = result_json.get("num_passed", 0)
|
| 90 |
+
pass_rate = num_passed / num_tests if num_tests > 0 else 0.0
|
| 91 |
+
|
| 92 |
+
# Structural integrity: to be done later
|
| 93 |
+
score = pass_rate
|
| 94 |
+
return score
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class RtlDebuggerEnvironment(Environment):
|
| 98 |
+
"""
|
| 99 |
+
RTL Debugging environment.
|
| 100 |
+
|
| 101 |
+
On reset(), a random task is selected from the tasks/ directory.
|
| 102 |
+
- design_buggy.v is read and shown to agent as the original reference.
|
| 103 |
+
- design_active.v is created as a fresh mutable copy of design_buggy.v.
|
| 104 |
+
|
| 105 |
+
On each step(), the agent submits revised code which:
|
| 106 |
+
1. Is written to design_active.v (overwrites the previous attempt).
|
| 107 |
+
2. Is compiled with iverilog — fatal gate if it fails.
|
| 108 |
+
3. Is simulated via `make` (cocotb + icarus).
|
| 109 |
+
4. Has result.json parsed for pass/fail metrics.
|
| 110 |
+
5. Levenshtein distance is measured from the *previous* design_active.v.
|
| 111 |
+
|
| 112 |
+
A separate grader() function computes the final normalized score [0,1].
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
SUPPORTS_CONCURRENT_SESSIONS: bool = True
|
| 116 |
+
|
| 117 |
+
def __init__(self):
|
| 118 |
+
"""Initialize the rtl_debugger environment."""
|
| 119 |
+
self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 120 |
+
self._task_dir: str = ""
|
| 121 |
+
self._design_code: str = "" # contents of design_buggy.v (immutable reference)
|
| 122 |
+
self._task_name: str = ""
|
| 123 |
+
|
| 124 |
+
@property
|
| 125 |
+
def _active_design_path(self) -> str:
|
| 126 |
+
return os.path.join(self._task_dir, "design_active.v")
|
| 127 |
+
|
| 128 |
+
def reset(self, options: dict | None = None) -> RtlDebuggerObservation: # type: ignore[override]
|
| 129 |
+
"""
|
| 130 |
+
Reset the environment and load a task.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
options: Optional dict that can contain 'TASK_NAME' to load a specific task.
|
| 134 |
+
If not provided or invalid, a random task is selected.
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
RtlDebuggerObservation with the initial design and feedback.
|
| 138 |
+
"""
|
| 139 |
+
self._state = State(episode_id=str(uuid4()), step_count=0)
|
| 140 |
+
|
| 141 |
+
tasks = _list_tasks()
|
| 142 |
+
if not tasks:
|
| 143 |
+
return RtlDebuggerObservation(
|
| 144 |
+
design_code="",
|
| 145 |
+
feedback=f"No tasks found in {_TASKS_DIR}.",
|
| 146 |
+
compiled=False,
|
| 147 |
+
passed_tests=False,
|
| 148 |
+
done=False,
|
| 149 |
+
reward=0.0,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
# Handle explicit task selection via options
|
| 153 |
+
selected_task_dir = None
|
| 154 |
+
if options and "TASK_NAME" in options:
|
| 155 |
+
target_name = options["TASK_NAME"]
|
| 156 |
+
for t_dir in tasks:
|
| 157 |
+
if os.path.basename(t_dir) == target_name:
|
| 158 |
+
selected_task_dir = t_dir
|
| 159 |
+
break
|
| 160 |
+
|
| 161 |
+
if not selected_task_dir:
|
| 162 |
+
selected_task_dir = random.choice(tasks)
|
| 163 |
+
|
| 164 |
+
self._task_dir = selected_task_dir
|
| 165 |
+
self._task_name = os.path.basename(self._task_dir)
|
| 166 |
+
buggy_path = os.path.join(self._task_dir, "design_buggy.v")
|
| 167 |
+
self._design_code = _read(buggy_path)
|
| 168 |
+
|
| 169 |
+
# Initialise design_active.v from the buggy design
|
| 170 |
+
shutil.copy(buggy_path, self._active_design_path)
|
| 171 |
+
|
| 172 |
+
return RtlDebuggerObservation(
|
| 173 |
+
design_code=self._design_code,
|
| 174 |
+
feedback=f"--- Task: {self._task_name} (Initial) ---\nLoaded. Fix the Verilog design so all tests pass.",
|
| 175 |
+
compiled=False,
|
| 176 |
+
passed_tests=False,
|
| 177 |
+
done=False,
|
| 178 |
+
reward=0.0,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
def step(self, action: RtlDebuggerAction) -> RtlDebuggerObservation: # type: ignore[override]
|
| 182 |
+
"""
|
| 183 |
+
Compile and simulate the submitted Verilog code against the task testbench.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
action: RtlDebuggerAction containing the revised code in fixed_code
|
| 187 |
+
|
| 188 |
+
Returns:
|
| 189 |
+
RtlDebuggerObservation with compilation/simulation results and reward metrics
|
| 190 |
+
"""
|
| 191 |
+
self._state.step_count += 1
|
| 192 |
+
code = action.fixed_code
|
| 193 |
+
|
| 194 |
+
try:
|
| 195 |
+
return self._step_impl(code)
|
| 196 |
+
except Exception as exc:
|
| 197 |
+
traceback.print_exc()
|
| 198 |
+
return RtlDebuggerObservation(
|
| 199 |
+
design_code=self._design_code,
|
| 200 |
+
feedback=f"[Internal Server Error] {type(exc).__name__}: {exc}",
|
| 201 |
+
compiled=False,
|
| 202 |
+
passed_tests=False,
|
| 203 |
+
pass_rate=0.0,
|
| 204 |
+
simulation_time=0.0,
|
| 205 |
+
levenshtein_distance=0,
|
| 206 |
+
reward=-1.0,
|
| 207 |
+
done=False,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
def _step_impl(self, code: str) -> RtlDebuggerObservation:
|
| 211 |
+
"""Inner step logic — writes to design_active.v and runs the testbench."""
|
| 212 |
+
|
| 213 |
+
# --- Levenshtein vs the *previous* design_active.v (last agent attempt) ---
|
| 214 |
+
prev_active = _read(self._active_design_path) if os.path.exists(self._active_design_path) else self._design_code
|
| 215 |
+
lev_distance = _levenshtein_line_distance(prev_active, code)
|
| 216 |
+
|
| 217 |
+
# --- 1. Write agent's code to design_active.v ---
|
| 218 |
+
with open(self._active_design_path, "w") as f:
|
| 219 |
+
f.write(code)
|
| 220 |
+
|
| 221 |
+
# --- 2. Compile check (mandatory gate) ---
|
| 222 |
+
compile_cmd = ["iverilog", "-t", "null", "design_active.v"]
|
| 223 |
+
compile_res = subprocess.run(
|
| 224 |
+
compile_cmd, cwd=self._task_dir, capture_output=True, text=True
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
if compile_res.returncode != 0:
|
| 228 |
+
feedback = compile_res.stderr or compile_res.stdout
|
| 229 |
+
return RtlDebuggerObservation(
|
| 230 |
+
design_code=self._design_code,
|
| 231 |
+
feedback=f"[Compile Error]\n{feedback}",
|
| 232 |
+
compiled=False,
|
| 233 |
+
passed_tests=False,
|
| 234 |
+
pass_rate=0.0,
|
| 235 |
+
simulation_time=0.0,
|
| 236 |
+
levenshtein_distance=lev_distance,
|
| 237 |
+
reward=-1.0,
|
| 238 |
+
done=False,
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
# --- 3. Run cocotb testbench via make in the task dir ---
|
| 242 |
+
try:
|
| 243 |
+
make_res = subprocess.run(
|
| 244 |
+
["make"],
|
| 245 |
+
cwd=self._task_dir,
|
| 246 |
+
capture_output=True,
|
| 247 |
+
text=True,
|
| 248 |
+
timeout=60,
|
| 249 |
+
)
|
| 250 |
+
make_feedback = make_res.stdout + make_res.stderr
|
| 251 |
+
except subprocess.TimeoutExpired:
|
| 252 |
+
return RtlDebuggerObservation(
|
| 253 |
+
design_code=self._design_code,
|
| 254 |
+
feedback="[Simulation Timeout] Simulation timed out (possible infinite loop in RTL)",
|
| 255 |
+
compiled=True,
|
| 256 |
+
passed_tests=False,
|
| 257 |
+
pass_rate=0.0,
|
| 258 |
+
simulation_time=0.0,
|
| 259 |
+
levenshtein_distance=lev_distance,
|
| 260 |
+
reward=-5.0,
|
| 261 |
+
done=False,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
# --- 4. Parse result.json (written by cocotb into the task dir) ---
|
| 265 |
+
result_path = os.path.join(self._task_dir, "result.json")
|
| 266 |
+
if not os.path.exists(result_path):
|
| 267 |
+
return RtlDebuggerObservation(
|
| 268 |
+
design_code=self._design_code,
|
| 269 |
+
feedback=f"[Simulation Error - result.json not produced]\n{make_feedback}",
|
| 270 |
+
compiled=True,
|
| 271 |
+
passed_tests=False,
|
| 272 |
+
pass_rate=0.0,
|
| 273 |
+
simulation_time=0.0,
|
| 274 |
+
levenshtein_distance=lev_distance,
|
| 275 |
+
reward=-5.0,
|
| 276 |
+
done=False,
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
with open(result_path, "r") as f:
|
| 280 |
+
result_data = json.load(f)
|
| 281 |
+
|
| 282 |
+
num_tests = result_data.get("num_tests", 1)
|
| 283 |
+
num_passed = result_data.get("num_passed", 0)
|
| 284 |
+
pass_rate = num_passed / num_tests if num_tests > 0 else 0.0
|
| 285 |
+
passed_all = result_data.get("passed", False)
|
| 286 |
+
simulation_time = result_data.get("simulation_time", 0.0)
|
| 287 |
+
|
| 288 |
+
reward = pass_rate * 10.0
|
| 289 |
+
reward += simulation_time * 0.01
|
| 290 |
+
reward -= lev_distance * 0.02
|
| 291 |
+
if passed_all:
|
| 292 |
+
reward += 20.0
|
| 293 |
+
|
| 294 |
+
feedback_lines = [
|
| 295 |
+
f"Compiled: OK | Tests: {num_passed}/{num_tests} passed | SimTime: {simulation_time} ns",
|
| 296 |
+
make_feedback.strip(),
|
| 297 |
+
]
|
| 298 |
+
feedback = "\n".join(filter(None, feedback_lines))
|
| 299 |
+
|
| 300 |
+
return RtlDebuggerObservation(
|
| 301 |
+
design_code=self._design_code,
|
| 302 |
+
feedback=feedback,
|
| 303 |
+
compiled=True,
|
| 304 |
+
passed_tests=passed_all,
|
| 305 |
+
pass_rate=pass_rate,
|
| 306 |
+
simulation_time=simulation_time,
|
| 307 |
+
levenshtein_distance=lev_distance,
|
| 308 |
+
reward=reward,
|
| 309 |
+
done=passed_all,
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
def grade(self) -> float:
|
| 313 |
+
"""
|
| 314 |
+
Public grader interface — call after the RL episode ends.
|
| 315 |
+
Reads result.json from the last make run and returns a score in [0, 1].
|
| 316 |
+
Returns 0.0 if no result.json exists yet.
|
| 317 |
+
"""
|
| 318 |
+
result_path = os.path.join(self._task_dir, "result.json")
|
| 319 |
+
if not self._task_dir or not os.path.exists(result_path):
|
| 320 |
+
return 0.0
|
| 321 |
+
with open(result_path, "r") as f:
|
| 322 |
+
result_data = json.load(f)
|
| 323 |
+
return grader(result_data, self._design_code, "")
|
| 324 |
+
|
| 325 |
+
@property
|
| 326 |
+
def state(self) -> State:
|
| 327 |
+
"""
|
| 328 |
+
Get the current environment state.
|
| 329 |
+
|
| 330 |
+
Returns:
|
| 331 |
+
Current State with episode_id and step_count
|
| 332 |
+
"""
|
| 333 |
+
return self._state
|
tasks/task2/context.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Four bit counter with reset signal
|
tasks/task2/design_active.v
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module gate (
|
| 2 |
+
input wire a,
|
| 3 |
+
input wire b,
|
| 4 |
+
output wire y
|
| 5 |
+
);
|
| 6 |
+
assign y = a ^ b;
|
| 7 |
+
endmodule
|
tasks/task2/design_buggy.v
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module gate (
|
| 2 |
+
input wire a,
|
| 3 |
+
input wire b,
|
| 4 |
+
output wire y
|
| 5 |
+
);
|
| 6 |
+
assign y = a & b;
|
| 7 |
+
endmodule
|
tasks/task2/makefile
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
TOPLEVEL_LANG = verilog
|
| 2 |
+
VERILOG_SOURCES = design_active.v
|
| 3 |
+
TOPLEVEL = gate
|
| 4 |
+
COCOTB_TEST_MODULES = test_xor_gate_simple
|
| 5 |
+
|
| 6 |
+
SIM = icarus
|
| 7 |
+
|
| 8 |
+
include $(shell cocotb-config --makefiles)/Makefile.sim
|
tasks/task2/result.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"passed": true,
|
| 3 |
+
"num_tests": 4,
|
| 4 |
+
"num_passed": 4,
|
| 5 |
+
"num_failed": 0,
|
| 6 |
+
"simulation_time": 4.0,
|
| 7 |
+
"results": [
|
| 8 |
+
{
|
| 9 |
+
"test_id": 0,
|
| 10 |
+
"inputs": {
|
| 11 |
+
"a": 0,
|
| 12 |
+
"b": 0
|
| 13 |
+
},
|
| 14 |
+
"expected": 0,
|
| 15 |
+
"actual": 0,
|
| 16 |
+
"pass": true
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"test_id": 1,
|
| 20 |
+
"inputs": {
|
| 21 |
+
"a": 0,
|
| 22 |
+
"b": 1
|
| 23 |
+
},
|
| 24 |
+
"expected": 1,
|
| 25 |
+
"actual": 1,
|
| 26 |
+
"pass": true
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"test_id": 2,
|
| 30 |
+
"inputs": {
|
| 31 |
+
"a": 1,
|
| 32 |
+
"b": 0
|
| 33 |
+
},
|
| 34 |
+
"expected": 1,
|
| 35 |
+
"actual": 1,
|
| 36 |
+
"pass": true
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"test_id": 3,
|
| 40 |
+
"inputs": {
|
| 41 |
+
"a": 1,
|
| 42 |
+
"b": 1
|
| 43 |
+
},
|
| 44 |
+
"expected": 0,
|
| 45 |
+
"actual": 0,
|
| 46 |
+
"pass": true
|
| 47 |
+
}
|
| 48 |
+
]
|
| 49 |
+
}
|
tasks/task2/results.xml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<testsuites name="results">
|
| 2 |
+
<testsuite name="all" package="all">
|
| 3 |
+
<property name="random_seed" value="1775413661" />
|
| 4 |
+
<testcase name="test_xor_gate_simple" classname="test_xor_gate_simple" file="/mnt/c/Users/npkas/Agentic-RL/rtl_debugger/tasks/task2/test_xor_gate_simple.py" lineno="6" time="0.0021092891693115234" sim_time_ns="4.0" ratio_time="1896.3734599299198" />
|
| 5 |
+
</testsuite>
|
| 6 |
+
</testsuites>
|
tasks/task2/sim_build/cmds.f
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
+timescale+1ns/1ps
|
tasks/task2/sim_build/sim.vvp
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#! /usr/bin/vvp
|
| 2 |
+
:ivl_version "12.0 (stable)";
|
| 3 |
+
:ivl_delay_selection "TYPICAL";
|
| 4 |
+
:vpi_time_precision - 12;
|
| 5 |
+
:vpi_module "/usr/lib/x86_64-linux-gnu/ivl/system.vpi";
|
| 6 |
+
:vpi_module "/usr/lib/x86_64-linux-gnu/ivl/vhdl_sys.vpi";
|
| 7 |
+
:vpi_module "/usr/lib/x86_64-linux-gnu/ivl/vhdl_textio.vpi";
|
| 8 |
+
:vpi_module "/usr/lib/x86_64-linux-gnu/ivl/v2005_math.vpi";
|
| 9 |
+
:vpi_module "/usr/lib/x86_64-linux-gnu/ivl/va_math.vpi";
|
| 10 |
+
:vpi_module "/usr/lib/x86_64-linux-gnu/ivl/v2009.vpi";
|
| 11 |
+
S_0x55e08223e510 .scope package, "$unit" "$unit" 2 1;
|
| 12 |
+
.timescale -9 -12;
|
| 13 |
+
S_0x55e08223e6a0 .scope module, "gate" "gate" 3 1;
|
| 14 |
+
.timescale -9 -12;
|
| 15 |
+
.port_info 0 /INPUT 1 "a";
|
| 16 |
+
.port_info 1 /INPUT 1 "b";
|
| 17 |
+
.port_info 2 /OUTPUT 1 "y";
|
| 18 |
+
o0x7f3d4edcc018 .functor BUFZ 1, C4<z>; HiZ drive
|
| 19 |
+
o0x7f3d4edcc048 .functor BUFZ 1, C4<z>; HiZ drive
|
| 20 |
+
L_0x55e082285170 .functor XOR 1, o0x7f3d4edcc018, o0x7f3d4edcc048, C4<0>, C4<0>;
|
| 21 |
+
v0x55e08224fd50_0 .net "a", 0 0, o0x7f3d4edcc018; 0 drivers
|
| 22 |
+
v0x55e082250430_0 .net "b", 0 0, o0x7f3d4edcc048; 0 drivers
|
| 23 |
+
v0x55e082285050_0 .net "y", 0 0, L_0x55e082285170; 1 drivers
|
| 24 |
+
# The file index is used to find the file name in the following table.
|
| 25 |
+
:file_names 4;
|
| 26 |
+
"N/A";
|
| 27 |
+
"<interactive>";
|
| 28 |
+
"-";
|
| 29 |
+
"design_active.v";
|
tasks/task2/test_xor_gate_simple.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cocotb
|
| 2 |
+
from cocotb.triggers import Timer
|
| 3 |
+
from cocotb.utils import get_sim_time
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
@cocotb.test()
|
| 7 |
+
async def test_xor_gate_simple(dut):
|
| 8 |
+
"""Test XOR gate with simple inputs (structured output)"""
|
| 9 |
+
|
| 10 |
+
results = []
|
| 11 |
+
passed = True
|
| 12 |
+
|
| 13 |
+
test_cases = [
|
| 14 |
+
{"a": 0, "b": 0, "expected": 0},
|
| 15 |
+
{"a": 0, "b": 1, "expected": 1},
|
| 16 |
+
{"a": 1, "b": 0, "expected": 1},
|
| 17 |
+
{"a": 1, "b": 1, "expected": 0},
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
for i, tc in enumerate(test_cases):
|
| 21 |
+
dut.a.value = tc["a"]
|
| 22 |
+
dut.b.value = tc["b"]
|
| 23 |
+
|
| 24 |
+
await Timer(1, unit="ns")
|
| 25 |
+
|
| 26 |
+
actual = int(dut.y.value)
|
| 27 |
+
ok = (actual == tc["expected"])
|
| 28 |
+
|
| 29 |
+
if not ok:
|
| 30 |
+
passed = False
|
| 31 |
+
|
| 32 |
+
results.append({
|
| 33 |
+
"test_id": i,
|
| 34 |
+
"inputs": {"a": tc["a"], "b": tc["b"]},
|
| 35 |
+
"expected": tc["expected"],
|
| 36 |
+
"actual": actual,
|
| 37 |
+
"pass": ok
|
| 38 |
+
})
|
| 39 |
+
|
| 40 |
+
summary = {
|
| 41 |
+
"passed": passed,
|
| 42 |
+
"num_tests": len(test_cases),
|
| 43 |
+
"num_passed": sum(r["pass"] for r in results),
|
| 44 |
+
"num_failed": sum(not r["pass"] for r in results),
|
| 45 |
+
"simulation_time": get_sim_time("ns"),
|
| 46 |
+
"results": results
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# ALWAYS write output (even if failing)
|
| 50 |
+
with open("result.json", "w") as f:
|
| 51 |
+
json.dump(summary, f, indent=2)
|
| 52 |
+
|
| 53 |
+
# Optional: still fail cocotb test for debugging (can remove later)
|
| 54 |
+
assert passed, "Some test cases failed"
|
uv.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
validate_submission.sh
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
#
|
| 3 |
+
# validate-submission.sh - OpenEnv Submission Validator
|
| 4 |
+
#
|
| 5 |
+
# Checks that your HF Space is live, Docker image builds, and openenv validate passes.
|
| 6 |
+
#
|
| 7 |
+
# Prerequisites:
|
| 8 |
+
# - Docker: https://docs.docker.com/get-docker/
|
| 9 |
+
# - openenv-core: pip install openenv-core
|
| 10 |
+
# - curl (usually pre-installed)
|
| 11 |
+
#
|
| 12 |
+
# Run:
|
| 13 |
+
# curl -fsSL https://raw.githubusercontent.com/<owner>/<repo>/main/scripts/validate-submission.sh | bash -s -- <ping_url> [repo_dir]
|
| 14 |
+
#
|
| 15 |
+
# Or download and run locally:
|
| 16 |
+
# chmod +x validate-submission.sh
|
| 17 |
+
# ./validate-submission.sh <ping_url> [repo_dir]
|
| 18 |
+
#
|
| 19 |
+
# Arguments:
|
| 20 |
+
# ping_url Your HuggingFace Space URL (e.g. https://your-space.hf.space)
|
| 21 |
+
# repo_dir Path to your repo (default: current directory)
|
| 22 |
+
#
|
| 23 |
+
# Examples:
|
| 24 |
+
# ./validate-submission.sh https://my-team.hf.space
|
| 25 |
+
# ./validate-submission.sh https://my-team.hf.space ./my-repo
|
| 26 |
+
#
|
| 27 |
+
|
| 28 |
+
set -uo pipefail
|
| 29 |
+
|
| 30 |
+
DOCKER_BUILD_TIMEOUT=600
|
| 31 |
+
if [ -t 1 ]; then
|
| 32 |
+
RED='\033[0;31m'
|
| 33 |
+
GREEN='\033[0;32m'
|
| 34 |
+
YELLOW='\033[1;33m'
|
| 35 |
+
BOLD='\033[1m'
|
| 36 |
+
NC='\033[0m'
|
| 37 |
+
else
|
| 38 |
+
RED='' GREEN='' YELLOW='' BOLD='' NC=''
|
| 39 |
+
fi
|
| 40 |
+
|
| 41 |
+
run_with_timeout() {
|
| 42 |
+
local secs="$1"; shift
|
| 43 |
+
if command -v timeout &>/dev/null; then
|
| 44 |
+
timeout "$secs" "$@"
|
| 45 |
+
elif command -v gtimeout &>/dev/null; then
|
| 46 |
+
gtimeout "$secs" "$@"
|
| 47 |
+
else
|
| 48 |
+
"$@" &
|
| 49 |
+
local pid=$!
|
| 50 |
+
( sleep "$secs" && kill "$pid" 2>/dev/null ) &
|
| 51 |
+
local watcher=$!
|
| 52 |
+
wait "$pid" 2>/dev/null
|
| 53 |
+
local rc=$?
|
| 54 |
+
kill "$watcher" 2>/dev/null
|
| 55 |
+
wait "$watcher" 2>/dev/null
|
| 56 |
+
return $rc
|
| 57 |
+
fi
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
portable_mktemp() {
|
| 61 |
+
local prefix="${1:-validate}"
|
| 62 |
+
mktemp "${TMPDIR:-/tmp}/${prefix}-XXXXXX" 2>/dev/null || mktemp
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
CLEANUP_FILES=()
|
| 66 |
+
cleanup() { rm -f "${CLEANUP_FILES[@]+"${CLEANUP_FILES[@]}"}"; }
|
| 67 |
+
trap cleanup EXIT
|
| 68 |
+
|
| 69 |
+
PING_URL="${1:-}"
|
| 70 |
+
REPO_DIR="${2:-.}"
|
| 71 |
+
|
| 72 |
+
if [ -z "$PING_URL" ]; then
|
| 73 |
+
printf "Usage: %s <ping_url> [repo_dir]\n" "$0"
|
| 74 |
+
printf "\n"
|
| 75 |
+
printf " ping_url Your HuggingFace Space URL (e.g. https://your-space.hf.space)\n"
|
| 76 |
+
printf " repo_dir Path to your repo (default: current directory)\n"
|
| 77 |
+
exit 1
|
| 78 |
+
fi
|
| 79 |
+
|
| 80 |
+
if ! REPO_DIR="$(cd "$REPO_DIR" 2>/dev/null && pwd)"; then
|
| 81 |
+
printf "Error: directory '%s' not found\n" "${2:-.}"
|
| 82 |
+
exit 1
|
| 83 |
+
fi
|
| 84 |
+
PING_URL="${PING_URL%/}"
|
| 85 |
+
export PING_URL
|
| 86 |
+
PASS=0
|
| 87 |
+
|
| 88 |
+
log() { printf "[%s] %b\n" "$(date -u +%H:%M:%S)" "$*"; }
|
| 89 |
+
pass() { log "${GREEN}PASSED${NC} -- $1"; PASS=$((PASS + 1)); }
|
| 90 |
+
fail() { log "${RED}FAILED${NC} -- $1"; }
|
| 91 |
+
hint() { printf " ${YELLOW}Hint:${NC} %b\n" "$1"; }
|
| 92 |
+
stop_at() {
|
| 93 |
+
printf "\n"
|
| 94 |
+
printf "${RED}${BOLD}Validation stopped at %s.${NC} Fix the above before continuing.\n" "$1"
|
| 95 |
+
exit 1
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
printf "\n"
|
| 99 |
+
printf "${BOLD}========================================${NC}\n"
|
| 100 |
+
printf "${BOLD} OpenEnv Submission Validator${NC}\n"
|
| 101 |
+
printf "${BOLD}========================================${NC}\n"
|
| 102 |
+
log "Repo: $REPO_DIR"
|
| 103 |
+
log "Ping URL: $PING_URL"
|
| 104 |
+
printf "\n"
|
| 105 |
+
|
| 106 |
+
log "${BOLD}Step 1/3: Pinging HF Space${NC} ($PING_URL/reset) ..."
|
| 107 |
+
|
| 108 |
+
CURL_OUTPUT=$(portable_mktemp "validate-curl")
|
| 109 |
+
CLEANUP_FILES+=("$CURL_OUTPUT")
|
| 110 |
+
HTTP_CODE=$(curl -s -o "$CURL_OUTPUT" -w "%{http_code}" -X POST \
|
| 111 |
+
-H "Content-Type: application/json" -d '{}' \
|
| 112 |
+
"$PING_URL/reset" --max-time 30 2>"$CURL_OUTPUT" || printf "000")
|
| 113 |
+
|
| 114 |
+
if [ "$HTTP_CODE" = "200" ]; then
|
| 115 |
+
pass "HF Space is live and responds to /reset"
|
| 116 |
+
elif [ "$HTTP_CODE" = "000" ]; then
|
| 117 |
+
fail "HF Space not reachable (connection failed or timed out)"
|
| 118 |
+
hint "Check your network connection and that the Space is running."
|
| 119 |
+
hint "Try: curl -s -o /dev/null -w '%%{http_code}' -X POST $PING_URL/reset"
|
| 120 |
+
stop_at "Step 1"
|
| 121 |
+
else
|
| 122 |
+
fail "HF Space /reset returned HTTP $HTTP_CODE (expected 200)"
|
| 123 |
+
hint "Make sure your Space is running and the URL is correct."
|
| 124 |
+
hint "Try opening $PING_URL in your browser first."
|
| 125 |
+
stop_at "Step 1"
|
| 126 |
+
fi
|
| 127 |
+
|
| 128 |
+
log "${BOLD}Step 2/3: Running docker build${NC} ..."
|
| 129 |
+
|
| 130 |
+
if ! command -v docker &>/dev/null; then
|
| 131 |
+
fail "docker command not found"
|
| 132 |
+
hint "Install Docker: https://docs.docker.com/get-docker/"
|
| 133 |
+
stop_at "Step 2"
|
| 134 |
+
fi
|
| 135 |
+
|
| 136 |
+
if [ -f "$REPO_DIR/Dockerfile" ]; then
|
| 137 |
+
DOCKER_CONTEXT="$REPO_DIR"
|
| 138 |
+
elif [ -f "$REPO_DIR/server/Dockerfile" ]; then
|
| 139 |
+
DOCKER_CONTEXT="$REPO_DIR/server"
|
| 140 |
+
else
|
| 141 |
+
fail "No Dockerfile found in repo root or server/ directory"
|
| 142 |
+
stop_at "Step 2"
|
| 143 |
+
fi
|
| 144 |
+
|
| 145 |
+
log " Found Dockerfile in $DOCKER_CONTEXT"
|
| 146 |
+
|
| 147 |
+
BUILD_OK=false
|
| 148 |
+
BUILD_OUTPUT=$(run_with_timeout "$DOCKER_BUILD_TIMEOUT" docker build "$DOCKER_CONTEXT" 2>&1) && BUILD_OK=true
|
| 149 |
+
|
| 150 |
+
if [ "$BUILD_OK" = true ]; then
|
| 151 |
+
pass "Docker build succeeded"
|
| 152 |
+
else
|
| 153 |
+
fail "Docker build failed (timeout=${DOCKER_BUILD_TIMEOUT}s)"
|
| 154 |
+
printf "%s\n" "$BUILD_OUTPUT" | tail -20
|
| 155 |
+
stop_at "Step 2"
|
| 156 |
+
fi
|
| 157 |
+
|
| 158 |
+
log "${BOLD}Step 3/3: Running openenv validate${NC} ..."
|
| 159 |
+
|
| 160 |
+
if ! command -v openenv &>/dev/null; then
|
| 161 |
+
fail "openenv command not found"
|
| 162 |
+
hint "Install it: pip install openenv-core"
|
| 163 |
+
stop_at "Step 3"
|
| 164 |
+
fi
|
| 165 |
+
|
| 166 |
+
VALIDATE_OK=false
|
| 167 |
+
VALIDATE_OUTPUT=$(cd "$REPO_DIR" && openenv validate 2>&1) && VALIDATE_OK=true
|
| 168 |
+
|
| 169 |
+
if [ "$VALIDATE_OK" = true ]; then
|
| 170 |
+
pass "openenv validate passed"
|
| 171 |
+
[ -n "$VALIDATE_OUTPUT" ] && log " $VALIDATE_OUTPUT"
|
| 172 |
+
else
|
| 173 |
+
fail "openenv validate failed"
|
| 174 |
+
printf "%s\n" "$VALIDATE_OUTPUT"
|
| 175 |
+
stop_at "Step 3"
|
| 176 |
+
fi
|
| 177 |
+
|
| 178 |
+
printf "\n"
|
| 179 |
+
printf "${BOLD}========================================${NC}\n"
|
| 180 |
+
printf "${GREEN}${BOLD} All 3/3 checks passed!${NC}\n"
|
| 181 |
+
printf "${GREEN}${BOLD} Your submission is ready to submit.${NC}\n"
|
| 182 |
+
printf "${BOLD}========================================${NC}\n"
|
| 183 |
+
printf "\n"
|
| 184 |
+
|