Skip to content

Commit 8830839

Browse files
authored
Merge pull request #60 from AI-Hypercomputer/luke-maxkernel-updates-after-testing
2 parents 948dedd + 5b60cb0 commit 8830839

12 files changed

Lines changed: 230 additions & 52 deletions

File tree

MaxKernel/auto_agent/config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
TPU_VERSION = os.environ.get("TPU_VERSION", "")
1313
RAG_CORPUS = os.environ.get("RAG_CORPUS", "")
1414
INCLUDE_THOUGHTS = os.environ.get("INCLUDE_THOUGHTS", "true").lower() == "true"
15+
MAX_COMPILATION_RETRIES = int(os.environ.get("MAX_COMPILATION_RETRIES", "6"))
1516

1617
# Model configuration
1718
model_config = types.GenerateContentConfig(

MaxKernel/auto_agent/subagents/kernel_writing/agent.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
load_kernel_and_plan_to_state,
1616
load_single_kernel_to_state,
1717
)
18-
from auto_agent.config import model_config, thinking_planner
18+
from auto_agent.config import model_config, thinking_planner, MAX_COMPILATION_RETRIES
1919
from auto_agent.constants import MODEL_NAME
2020
from auto_agent.custom_types import CustomLlmAgent
2121
from auto_agent.subagents.kernel_writing.kernel_compilation import (
@@ -45,15 +45,15 @@ class KernelCompilationValidationLoop(BaseAgent):
4545
compilation_checker: Optional[BaseAgent] = None
4646
fix_agent: Optional[BaseAgent] = None
4747
debug_agent: Optional[BaseAgent] = None
48-
max_retries: int = 4
48+
max_retries: int = 6
4949

5050
def __init__(
5151
self,
5252
name: str,
5353
compilation_checker: BaseAgent,
5454
fix_agent: BaseAgent,
5555
debug_agent: Optional[BaseAgent] = None,
56-
max_retries: int = 4,
56+
max_retries: int = 6,
5757
):
5858
super().__init__(
5959
name=name,
@@ -351,7 +351,7 @@ async def _run_async_impl(
351351
compilation_checker=kernel_compilation_checker_for_validation,
352352
fix_agent=fix_kernel_compilation_agent,
353353
debug_agent=add_debug_statements_agent,
354-
max_retries=6,
354+
max_retries=MAX_COMPILATION_RETRIES,
355355
)
356356

357357
kernel_compilation_summary_agent = CustomLlmAgent(

MaxKernel/auto_agent/subagents/kernel_writing/prompts/ask_validation_prompt.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
YOUR TASK:
99
Present the user with clear options for what to do next:
1010
11-
1. **Validate & Auto-Fix Compilation**: Run automatic compilation validation with error fixing (up to 4 attempts)
11+
1. **Validate & Auto-Fix Compilation**: Run automatic compilation validation with error fixing (includes up to 6 automatic error-fixing attempts; you can ask me to change this limit at any time)
1212
2. **Generate Tests**: Skip validation and proceed directly to test generation
1313
3. **Something Else**: Ask a question or perform another action
1414

MaxKernel/hitl_agent/agent.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,11 @@
3131
unified_test_agent,
3232
validated_test_generation_agent,
3333
)
34-
from hitl_agent.tools.tools import filesystem_tool_r
34+
from hitl_agent.tools.tools import (
35+
filesystem_tool_r,
36+
set_working_directory,
37+
set_max_compilation_retries,
38+
)
3539

3640
# Root orchestration agent
3741
root_agent = CustomLlmAgent(
@@ -56,7 +60,9 @@
5660
autotune_agent, # Step 7: Auto-tune kernel
5761
],
5862
tools=[
59-
filesystem_tool_r
63+
filesystem_tool_r,
64+
set_working_directory,
65+
set_max_compilation_retries,
6066
], # Read-only access - orchestrator delegates writes to sub-agents
6167
instruction=interactive_prompt.PROMPT,
6268
description="Orchestrates the human-in-the-loop kernel generation process with GPU to JAX conversion capability.",

MaxKernel/hitl_agent/config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
TPU_VERSION = os.environ.get("TPU_VERSION", "")
1313
RAG_CORPUS = os.environ.get("RAG_CORPUS", "")
1414
INCLUDE_THOUGHTS = os.environ.get("INCLUDE_THOUGHTS", "true").lower() == "true"
15+
MAX_COMPILATION_RETRIES = int(os.environ.get("MAX_COMPILATION_RETRIES", "6"))
1516

1617
# Model configuration
1718
model_config = types.GenerateContentConfig(

MaxKernel/hitl_agent/prompts/interactive_prompt.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@
1010
### Your Capabilities
1111
1212
1. **Filesystem Tool (Read-Only)**: You have a `filesystem_tool` that can **only read and list files** - you cannot write files. All file writing must be delegated to the appropriate sub-agents. Assume that all files you need to read are located in {workdir}. For example, if the user asks to read file `script.py`, you should call the tool with the path `{workdir}/script.py`.
13-
2. **Specialist Sub-Agents**: You have a team of sub-agents you can delegate tasks to:
13+
2. **Set Working Directory Tool**: You have a `set_working_directory` tool that can update the active workspace/working directory path for the session. Use this tool when the user requests to switch, set, or change the active working directory or workspace folder.
14+
3. **Set Max Compilation Retries Tool**: You have a `set_max_compilation_retries` tool that can update the maximum number of compilation validation and auto-fixing attempts. Use this tool when the user requests to set or change the maximum compilation retries or fixing attempts count.
15+
4. **Specialist Sub-Agents**: You have a team of sub-agents you can delegate tasks to:
1416
* **PlanKernelAgent**: Creates or revises optimization plans for Pallas kernels. Automatically presents plans to the user with approval options. Use for both new plans ("optimize X") and revisions ("change Y in the plan").
1517
* **ImplementKernelAgent**: Implements a Pallas kernel following an approved plan. Use ONLY after user approves the plan. Automatically asks the user about validation options after completion.
16-
* **ValidateKernelCompilationAgent**: Validates kernel compilation with automatic error fixing and debugging (up to 4 attempts). Use when user requests validation or wants to check compilation.
18+
* **ValidateKernelCompilationAgent**: Validates kernel compilation with automatic error fixing and debugging (up to 6 attempts by default; the user can ask you to change this limit). Use when user requests validation or wants to check compilation.
1719
* **ExplanationAgent**: Explains TPU or Pallas concepts.
1820
* **GenerateTestFileAgent**: Generates a comprehensive pytest test file with compilation, correctness, and performance tests for kernel files.
1921
* **UnifiedTestAgent**: Executes the generated pytest test file on TPU and provides comprehensive results including full tracebacks. Automatically manages server lifecycle (starts/stops TPU and eval servers as needed).
@@ -33,9 +35,19 @@
3335
* Is it test execution? (e.g., "Run the tests", "Test the kernels")
3436
* Is it profiling? (e.g., "Profile the kernel", "What are the bottlenecks?")
3537
* Is it GPU conversion? (e.g., "Convert CUDA to JAX", "Write JAX from PyTorch")
38+
* Is it setting/changing the workspace or working directory? (e.g., "Change working directory to /path/to/folder", "Set workspace folder to Y")
39+
* Is it changing the maximum compilation retries or attempts? (e.g., "Set max retries to 8", "Change max fixing attempts to 10")
3640
3741
2. **Execute the Plan**:
3842
43+
* **If the request is to CHANGE/SET the workspace or working directory**:
44+
* **Action**: Call `set_working_directory` tool with the absolute path.
45+
* **Note**: Set `persist=True` ONLY if the user explicitly asks to persist, save, or make the change permanent. Otherwise, leave it as `False` (default).
46+
47+
* **If the request is to CHANGE/SET the maximum compilation retries**:
48+
* **Action**: Call `set_max_compilation_retries` tool with the integer value.
49+
* **Note**: Set `persist=True` ONLY if the user explicitly asks to persist, save, or make the change permanent. Otherwise, leave it as `False` (default).
50+
3951
* **If the request is simple explanation** (like "What is a TPU?"):
4052
* **Action**: Delegate to `ExplanationAgent`.
4153

MaxKernel/hitl_agent/subagents/kernel_writing/agent.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
load_single_kernel_to_state,
1616
save_kernel_and_plan_paths,
1717
)
18-
from hitl_agent.config import model_config, thinking_planner
18+
from hitl_agent.config import model_config, thinking_planner, MAX_COMPILATION_RETRIES
1919
from hitl_agent.constants import MODEL_NAME
2020
from hitl_agent.custom_types import CustomLlmAgent
2121
from hitl_agent.subagents.kernel_writing.kernel_compilation import (
@@ -41,15 +41,15 @@ class KernelCompilationValidationLoop(BaseAgent):
4141
compilation_checker: Optional[BaseAgent] = None
4242
fix_agent: Optional[BaseAgent] = None
4343
debug_agent: Optional[BaseAgent] = None
44-
max_retries: int = 4
44+
max_retries: int = 6
4545

4646
def __init__(
4747
self,
4848
name: str,
4949
compilation_checker: BaseAgent,
5050
fix_agent: BaseAgent,
5151
debug_agent: Optional[BaseAgent] = None,
52-
max_retries: int = 4,
52+
max_retries: int = 6,
5353
):
5454
super().__init__(
5555
name=name,
@@ -372,7 +372,7 @@ async def _run_async_impl(
372372
compilation_checker=kernel_compilation_checker_for_validation,
373373
fix_agent=fix_kernel_compilation_agent,
374374
debug_agent=add_debug_statements_agent,
375-
max_retries=4,
375+
max_retries=MAX_COMPILATION_RETRIES,
376376
)
377377

378378
kernel_compilation_summary_agent = CustomLlmAgent(

MaxKernel/hitl_agent/subagents/kernel_writing/prompts/ask_validation_prompt.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
YOUR TASK:
99
Present the user with clear options for what to do next:
1010
11-
1. **Validate & Auto-Fix Compilation**: Run automatic compilation validation with error fixing (up to 4 attempts)
11+
1. **Validate & Auto-Fix Compilation**: Run automatic compilation validation with error fixing (includes up to 6 automatic error-fixing attempts; you can ask me to change this limit at any time)
1212
2. **Generate Tests**: Skip validation and proceed directly to test generation
1313
3. **Something Else**: Ask a question or perform another action
1414
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""Filesystem tools configuration for the HITL agent."""
2+
3+
import os
4+
from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams
5+
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset
6+
from mcp import StdioServerParameters
7+
8+
from hitl_agent.config import WORKDIR
9+
10+
# Read-only filesystem tool for orchestration agent (no write access)
11+
filesystem_tool_r = MCPToolset(
12+
connection_params=StdioConnectionParams(
13+
server_params=StdioServerParameters(
14+
command="npx",
15+
args=[
16+
"-y", # Argument for npx to auto-confirm install
17+
"@modelcontextprotocol/server-filesystem@0.5.1",
18+
os.path.abspath(WORKDIR),
19+
],
20+
),
21+
),
22+
# Optional: Filter which tools from the MCP server are exposed
23+
tool_filter=["list_directory", "read_file"],
24+
)
25+
26+
# Read-write filesystem tool for sub-agents
27+
filesystem_tool_rw = MCPToolset(
28+
connection_params=StdioConnectionParams(
29+
server_params=StdioServerParameters(
30+
command="npx",
31+
args=[
32+
"-y", # Argument for npx to auto-confirm install
33+
"@modelcontextprotocol/server-filesystem@0.5.1",
34+
os.path.abspath(WORKDIR),
35+
],
36+
),
37+
),
38+
# Optional: Filter which tools from the MCP server are exposed
39+
tool_filter=["list_directory", "read_file", "write_file"],
40+
)
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""Tool for dynamically updating the max compilation retries setting."""
2+
3+
import logging
4+
import os
5+
from google.adk.tools import FunctionTool, ToolContext
6+
7+
8+
async def set_max_compilation_retries_fn(
9+
retries: int, tool_context: ToolContext, persist: bool = False
10+
) -> str:
11+
"""Set the maximum number of compilation validation and auto-fixing attempts.
12+
13+
Args:
14+
retries: The maximum number of attempts (must be positive).
15+
persist: Whether to permanently save this change to the configuration file (default is False).
16+
17+
Returns:
18+
A string containing the operation result description:
19+
- If successful: "Successfully updated maximum compilation retries to: <retries> (persisted: <persist>)"
20+
- If failed: "Error: The number of retries must be a positive integer."
21+
"""
22+
if retries <= 0:
23+
return "Error: The number of retries must be a positive integer."
24+
25+
# Update in-memory config variables
26+
import hitl_agent.config as hitl_cfg
27+
hitl_cfg.MAX_COMPILATION_RETRIES = retries
28+
os.environ["MAX_COMPILATION_RETRIES"] = str(retries)
29+
30+
# Update .env file if persist is requested
31+
if persist:
32+
try:
33+
env_path = ".env"
34+
if os.path.exists(env_path):
35+
with open(env_path, "r") as f:
36+
lines = f.readlines()
37+
with open(env_path, "w") as f:
38+
updated = False
39+
for line in lines:
40+
if line.strip().startswith("MAX_COMPILATION_RETRIES="):
41+
f.write(f"MAX_COMPILATION_RETRIES={retries}\n")
42+
updated = True
43+
else:
44+
f.write(line)
45+
if not updated:
46+
f.write(f"MAX_COMPILATION_RETRIES={retries}\n")
47+
except Exception as e:
48+
logging.error(f"Failed to update .env: {e}")
49+
50+
# Update the active validation loops in-memory
51+
try:
52+
from hitl_agent.subagents.kernel_writing.agent import kernel_compilation_validation_loop as hitl_loop
53+
hitl_loop.max_retries = retries
54+
except Exception as e:
55+
logging.warning(f"Could not update hitl_loop max_retries: {e}")
56+
57+
return f"Successfully updated maximum compilation retries to: {retries} (persisted: {persist})"
58+
59+
60+
set_max_compilation_retries = FunctionTool(set_max_compilation_retries_fn)

0 commit comments

Comments
 (0)