The user wants an ML experiment tracking CLI.
Key features:
Sync metadata.
Push diff summaries.
Enforce naming conventions.
This is a tool for managing machine learning experiments, likely interacting with a remote tracking server (like MLflow, Weights & Biases, or a custom backend) and a Git repository.
Core Components:
Configuration: Needs a config file (e.g., .mltrack.yaml or pyproject.toml) to define project name, backend URL, and naming rules.
CLI Interface: A command-line tool using click or typer.
init: Set up the project.
run <command>: Execute a script while tracking it.
sync: Push local metadata to the remote.
diff: Show differences between experiments or commits.
enforce (or hooks): Validate names/parameters.
Metadata Syncing:
Local storage (SQLite or JSON files in a .mltrack directory) for offline robustness.
Remote sync logic.
Diff Summaries:
Comparing parameters, metrics, and code diffs (git).
Naming Conventions:
Regex validation for experiment names.
Tags enforcement.
High-Level Architecture:
Language: Python is the standard for ML.
Framework: typer for the CLI (modern, easy), rich for pretty output.
Backend: Mock/Abstract interface for the tracking server (to keep it generic, or I can simulate a local file-based backend for the demo).
Git Integration: gitpython or direct subprocess calls.
Detailed Design Steps:
Project Structure:
ml_tracker/
__init__.py
cli.py (Entry point)
core.py (Logic for tracking, diffing)
config.py (Settings management)
naming.py (Validators)
storage.py (Local/Remote handling)
Feature 1: Naming Conventions
Define a regex pattern in config.
Function validate_name(name: str, pattern: str).
Integrate into the run command or a pre-commit hook.
I will implement a complete, runnable Python package structure. I will use typer for the CLI, pydantic for configuration validation, and standard library json/pathlib for the mock storage to ensure the code is standalone and executable.
Config: pyproject.toml is too complex to parse from scratch without toml library (standard in Python 3.11, but let's stick to yaml or just a python dict for simplicity, or assume toml is available). Let's use a .mltrack.json file for simplicity in the demo.
Diff Logic:
It needs to capture git info. I'll simulate git info or use subprocess.
Sync Logic:
A MetadataStore class.
post method (simulated).
Step-by-Step Implementation Plan:
Imports & Setup: typer, pydantic, rich.
Configuration: Schema for naming conventions and project info.
Storage: A class to handle reading/writing experiment data locally and "syncing".
Git Integration: Helper to get current commit/diff.
Naming Enforcer: Logic to check experiment names.
CLI Commands:
init: Create config.
run: Log params, run script (simulated), check naming.
diff: Compare runs.
sync: Push to "cloud".
Self-Correction/Edge Cases:
What if git isn't initialized? Handle gracefully.
How to capture diffs? We need to save the git SHA when an experiment starts.
How to enforce naming? Raise an error if the name doesn't match the regex.
Let's write the code. I'll provide a single comprehensive file solution (or a structured representation) that can be split into a package.
Key Classes:
ExperimentConfig: Pydantic model.
ExperimentTracker: Context manager for logging.
Backend: Abstraction for storage.
Enforcer: Regex checker.
The "Diff" Feature:
The user wants to "push diff summaries". This implies when syncing, we might summarize what changed compared to the previous best model or the base commit. I will implement a generate_diff_summary(run_a, run_b) function.
Let's assemble the Python solution. I'll use typer as it's the modern standard.
Structure of the response:
Project overview.
Code implementation (the CLI library).
Usage examples (How to use it).
Explanation of key design decisions.
(Self-Correction during coding): I need to make sure the "Run" command actually executes something? Or just creates a record? A tracker usually wraps execution. I'll implement a track decorator/context manager and a cli run command that wraps a python script.
Actually, for a "Design" prompt, providing a robust library code + CLI wrapper is best.
Dependencies:typer, rich, pydantic, gitpython (optional, but easier to mock subprocess to avoid deps in the example, though gitpython is better for real world). I will stick to subprocess for git to keep dependencies low in the example, but mention gitpython.
Let's refine the "Enforce Naming" part.
It should happen at experiment creation.
Let's refine "Push Diff Summaries".
When running sync, it calculates the diff between the local run and the remote "production" tag (or last synced run) and attaches that text to the payload.
Let's write it.
This design outlines a Python CLI tool called ml-sync. It uses typer for the CLI framework, pydantic for configuration validation, and standard git commands for version control integration.
1. Architecture Overview
The tool is built around three core pillars:
Configuration Store (.ml-sync.yaml): Defines project naming rules and remote endpoints.
Metadata Manager: Handles the local database (SQLite/JSON) of experiments and calculates diffs.
Git Interface: Extracts commit hashes and generates diff summaries to link code changes to metric changes.
2. Project Setup
Directory Structure:
text
ml_sync/
├── __init__.py
├── cli.py # Entry point for commands
├── config.py # Pydantic models for validation
├── tracker.py # Core logic (metadata, git, diff)
└── storage.py # Local persistence layer
We use Pydantic to enforce types and regex patterns for naming conventions.
python
import re
from pathlib import Path
from typing import Optional, List
from pydantic import BaseModel, Field, field_validator
class NamingConvention(BaseModel):
experiment_pattern: str = r"^[a-z]+-[0-9]{4}$" # e.g., "bert-0023"
max_length: int = 32
@field_validator('experiment_pattern')
def check_regex(cls, v):
try:
re.compile(v)
except re.error:
raise ValueError("Invalid regex pattern for naming convention")
return v
class Config(BaseModel):
project_name: str
remote_url: Optional[str] = None
naming: NamingConvention = NamingConvention()
required_tags: List[str] = []
def load_config():
config_path = Path(".ml-sync.yaml")
if not config_path.exists():
raise FileNotFoundError("Config file .ml-sync.yaml not found. Run 'ml-sync init'.")
# In a real app, use yaml library to load dict and pass to Config
# Simulating a config for this example:
return Config(project_name="default-project")
B. Storage & Git Logic (tracker.py)
This module handles the heavy lifting: validating names, talking to Git, and calculating metric diffs.
python
C. CLI Interface (cli.py)
The user-facing commands using typer.
python
import typer
import json
from typing import Dict
from rich.console import Console
from tracker import ExperimentTracker
app = typer.Typer()
console = Console()
@app.command()
def init(project_name: str):
"""Initialize a new ml-sync project."""
console.print(f"[bold green]Initializing project: {project_name}[/bold green]")
# Create default config logic here
with open(".ml-sync.yaml", "w") as f:
f.write(f"project_name: {project_name}\nnaming:\n experiment_pattern: '^[a-z]+-[0-9]{4}$'\n")
@app.command()
def run(
name: str = typer.Argument(..., help="Name of the experiment"),
params: str = typer.Option("{}", help="JSON string of parameters"),
metrics: str = typer.Option("{}", help="JSON string of metrics")
):
"""Log a new experiment run."""
try:
tracker = ExperimentTracker()
# Parse JSON inputs
params_dict = json.loads(params)
metrics_dict = json.loads(metrics)
tracker.log_experiment(name, params_dict, metrics_dict)
except ValueError as e:
console.print(f"[bold red]Validation Error:[/bold red] {e}")
raise typer.Exit(code=1)
except Exception as e:
console.print(f"[bold red]Error:[/bold red] {e}")
raise typer.Exit(code=1)
@app.command()
def diff(exp_a: str, exp_b: str):
"""Compare metrics between two experiments."""
tracker = ExperimentTracker()
state = tracker._load_state()
if exp_a not in state['experiments'] or exp_b not in state['experiments']:
console.print("[red]Experiments not found.[/red]")
return
data_a = state['experiments'][exp_a]
data_b = state['experiments'][exp_b]
console.print(f"[cyan]Comparing {exp_a} vs {exp_b}[/cyan]")
# Simple Metric Diff Logic
metrics_a = data_a['metrics']
metrics_b = data_b['metrics']
for key in set(metrics_a.keys()) | set(metrics_b.keys()):
val_a = metrics_a.get(key, 0)
val_b = metrics_b.get(key, 0)
delta = float(val_b) - float(val_a)
color = "green" if delta > 0 else "red"
console.print(f"{key}: {val_a} -> {val_b} [{color}]{delta:+.4f}[/{color}]")
@app.command()
def sync():
"""Sync local metadata to remote."""
tracker = ExperimentTracker()
tracker.sync()
if __name__ == "__main__":
app()
4. How to Use
Step 1: Initialize
bash
python cli.py init my-ml-project
Step 2: Run Experiments
The user must adhere to the regex ^[a-z]+-[0-9]{4}$ (e.g., test-0001).
Naming Enforcement: Inside tracker.py, validate_name checks the input string against a regex defined in config.py. This prevents "analysis paralysis" where team members use inconsistent names like test_final_v2 vs best_model_3.
Diff Summaries: generate_diff_summary runs git diff --shortstat between the commit of the current experiment and the previous experiment. This automatically answers "What code changed caused this metric shift?".
Metadata Sync: The sync command bundles the JSON state. In a production scenario, requests.post would send this to an API (FastAPI, MLflow, etc.).
import subprocess
import json
import hashlib
from datetime import datetime
from pathlib import Path
from typing import Dict, Any, Optional
from config import Config, load_config
class ExperimentTracker:
def __init__(self):
self.config = load_config()
self.db_path = Path(".ml-sync-state.json")
self._ensure_storage()
def _ensure_storage(self):
if not self.db_path.exists():
self._save_state({"experiments": {}})
def _load_state(self) -> Dict:
return json.loads(self.db_path.read_text())
def _save_state(self, data: Dict):
self.db_path.write_text(json.dumps(data, indent=2))
def validate_name(self, name: str) -> bool:
if len(name) > self.config.naming.max_length:
return False
return bool(re.match(self.config.naming.experiment_pattern, name))
def get_git_meta(self) -> Dict[str, str]:
"""Extracts current commit hash and branch."""
try:
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf-8').strip()
branch = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode('utf-8').strip()
return {"commit": commit, "branch": branch}
except subprocess.CalledProcessError:
return {"commit": "unknown", "branch": "unknown"}
def generate_diff_summary(self, commit_a: str, commit_b: str) -> str:
"""Generates a text summary of code changes between two commits."""
if "unknown" in [commit_a, commit_b]:
return "Cannot generate diff for unknown commits."
try:
# Get stats summary (e.g., "5 files changed, 20 insertions(+)")
cmd = ['git', 'diff', '--shortstat', commit_a, commit_b]
result = subprocess.check_output(cmd).decode('utf-8').strip()
return result if result else "No code changes detected."
except Exception as e:
return f"Error generating diff: {str(e)}"
def log_experiment(self, name: str, params: Dict, metrics: Dict):
if not self.validate_name(name):
raise ValueError(f"Experiment name '{name}' violates naming convention: {self.config.naming.experiment_pattern}")
git_meta = self.get_git_meta()
state = self._load_state()
# Detect previous commit to generate diff
last_exp = state.get("last_run_commit")
code_diff = ""
if last_exp and last_exp != git_meta['commit']:
code_diff = self.generate_diff_summary(last_exp, git_meta['commit'])
exp_data = {
"timestamp": datetime.now().isoformat(),
"params": params,
"metrics": metrics,
"git": git_meta,
"code_diff_summary": code_diff
}
state["experiments"][name] = exp_data
state["last_run_commit"] = git_meta['commit']
self._save_state(state)
print(f"✅ Logged experiment: {name}")
if code_diff:
print(f"📝 Code Diff: {code_diff}")
def sync(self):
"""Simulates pushing metadata to a remote server."""
state = self._load_state()
payload = {
"project": self.config.project_name,
"data": state["experiments"]
}
# In a real scenario, use requests.post(self.config.remote_url, json=payload)
print(f"🚀 Syncing {len(payload['data'])} experiments to {self.config.remote_url or 'Local Console'}...")
print(json.dumps(payload, indent=2))
print("✅ Sync complete.")