# Project export: Stable-RL

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: TreeHacks 2025
- Tagline: Offline RL is historically bad out of distribution. We created an OSS to fix this using conformal prediction.
- Devpost: https://devpost.com/software/stable-rl
- GitHub: https://github.com/khushgx/cql
- Demo: https://v0-stable-rl-spncmb.vercel.app/
- Team: 1 GitHub contributor(s) — Khush Gupta (5 commits)

## Devpost submission (written by the team)

### Inspiration

Reinforcement Learning (RL) has achieved significant success in decision-making tasks but struggles with real-world applications where interaction with the environment is expensive or dangerous. Offline RL attempts to address this by learning from fixed datasets, but suffers from Q-value overestimation on out-of-distribution (OOD) state-action pairs. The Conformal Q-Learning approach seeks to mitigate these issues by integrating conformal prediction into RL. This method provides distribution-free uncertainty quantification with finite-sample guarantees, helping to stabilize policy learning and prevent overestimation errors. The approach is particularly relevant for safety-critical applications where robust decision-making is necessary.

### What it does

Conformal Q-Learning enhances standard RL algorithms by introducing statistical confidence intervals around Q-value estimates. It ensures that: Learned Q-values remain within prediction intervals with high probability. Uncertainty quantification helps mitigate overestimation and unsafe policy decisions. Policies become more stable and robust to OOD state-action pairs. It improves conservatism and optimism balance, performing better than traditional Conservative Q-Learning (CQL) approaches.

### How we built it

The Conformal Q-Learning framework was developed by integrating conformal prediction into an actor-critic RL setup, specifically for offline RL. The methodology includes: Q-Network Training: A deep Q-network is trained to estimate Q-values based on historical data. Conformal Interval Calibration: During training, nonconformity scores are computed using a calibration set to construct prediction intervals. Actor-Critic Framework: The actor network (policy) is updated to maximize Q-values, incorporating the uncertainty information from conformal intervals. Empirical evaluations were conducted on CartPole-v1 using offline RL datasets, validating the effectiveness of Conformal Q-Learning.

### Challenges we ran into

Handling OOD Actions – Offline RL suffers from extrapolation errors, and ensuring robust Q-value estimates in unseen states was non-trivial. Balancing Conservatism & Optimism – Unlike CQL, which applies a fixed penalty, conformal prediction needed fine-tuned quantile selection. Computational Constraints – Ensuring that conformal interval calibration remains computationally feasible without excessive overhead. Stability in Training – Traditional RL algorithms can suffer from instability, particularly when using confidence intervals in decision-making.

### Accomplishments we're proud of

Empirical Success: Demonstrated improved policy stability, robustness to OOD data, and enhanced performance compared to CQL and standard DQN. First-of-its-kind integration of conformal prediction into Q-learning for uncertainty quantification in RL.

### What we learned

Uncertainty estimation is critical in RL, particularly for offline settings where exploration is limited. Accelerating RL training with PyTorch optimizations: Leveraging techniques such as torch.jit for just-in-time (JIT) compilation, CUDA acceleration, and efficient tensor operations can significantly speed up Q-network training and conformal interval calculations, making the approach more scalable for real-world applications.

### What's next

We are looking to expand the amount of algorithms that we can integrate this in. Currently, we had time to implement this idea with Soft-Actor Critic, but integrating this uncertainty quantification into more popular algorithms is our next goal. Additionally testing its robustness on edge-based scenarios, like autonomous driving, is a plausible next step as our motivation was centered around improving robustness in these areas

## README (from the GitHub repository)

## Inspiration
Reinforcement Learning (RL) has achieved significant success in decision-making tasks but struggles with real-world applications where interaction with the environment is expensive or dangerous. Offline RL attempts to address this by learning from fixed datasets, but suffers from Q-value overestimation on out-of-distribution (OOD) state-action pairs.

The Conformal Q-Learning approach seeks to mitigate these issues by integrating conformal prediction into RL. This method provides distribution-free uncertainty quantification with finite-sample guarantees, helping to stabilize policy learning and prevent overestimation errors. The approach is particularly relevant for safety-critical applications where robust decision-making is necessary.

## What it does
Conformal Q-Learning enhances standard RL algorithms by introducing statistical confidence intervals around Q-value estimates. It ensures that:
- Learned Q-values remain within prediction intervals with high probability.
- Uncertainty quantification helps mitigate overestimation and unsafe policy decisions.
- Policies become more stable and robust to OOD state-action pairs.
- It improves conservatism and optimism balance, performing better than traditional Conservative Q-Learning (CQL) approaches.

## How we built it

The Conformal Q-Learning framework was developed by integrating conformal prediction into an actor-critic RL setup, specifically for offline RL. The methodology includes:

- Q-Network Training: A deep Q-network is trained to estimate Q-values based on historical data.
- Conformal Interval Calibration: During training, nonconformity scores are computed using a calibration set to construct prediction intervals.
- Actor-Critic Framework: The actor network (policy) is updated to maximize Q-values, incorporating the uncertainty information from conformal intervals.
- Empirical evaluations were conducted on CartPole-v1 using offline RL datasets, validating the effectiveness of Conformal Q-Learning.

## Challenges we ran into
1. Handling OOD Actions – Offline RL suffers from extrapolation errors, and ensuring robust Q-value estimates in unseen states was non-trivial.
2. Balancing Conservatism & Optimism – Unlike CQL, which applies a fixed penalty, conformal prediction needed fine-tuned quantile selection.
3. Computational Constraints – Ensuring that conformal interval calibration remains computationally feasible without excessive overhead.
4. Stability in Training – Traditional RL algorithms can suffer from instability, particularly when using confidence intervals in decision-making.

## Accomplishments that we're proud of
- Empirical Success: Demonstrated improved policy stability, robustness to OOD data, and enhanced performance compared to CQL and standard DQN.
- First-of-its-kind integration of conformal prediction into Q-learning for uncertainty quantification in RL.

## What we learned
- Uncertainty estimation is critical in RL, particularly for offline settings where exploration is limited.
- Accelerating RL training with PyTorch optimizations: Leveraging techniques such as torch.jit for just-in-time (JIT) compilation, CUDA acceleration, and efficient tensor operations can significantly speed up Q-network training and conformal interval calculations, making the approach more scalable for real-world applications.

## What's next for Stable-RL
We are looking to expand the amount of algorithms that we can integrate this in. Currently, we had time to implement this idea with Soft-Actor Critic, but integrating this uncertainty quantification into more popular algorithms is our next goal. Additionally testing its robustness on edge-based scenarios, like autonomous driving, is a plausible next step as our motivation was centered around improving robustness in these areas


## Detected evidence (automated analysis)

Indexed codebase: 79 recognized source files, 296 KB.
- CSS (language) — detected in the code
- Next.js (technology) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- PyTorch (technology) — claimed on Devpost, not found in the code
- Vercel (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (86 of 86)

```
.DS_Store
conformal_agent/agent_wrapper.py
conformal_agent/agents.py
frontend/.gitignore
frontend/app/docs/api/configuration/page.tsx
frontend/app/docs/api/conformal-q-learning/page.tsx
frontend/app/docs/api/utilities/page.tsx
frontend/app/docs/conformal-prediction/page.tsx
frontend/app/docs/conformal-q-learning/page.tsx
frontend/app/docs/globals.css
frontend/app/docs/installation/page.tsx
frontend/app/docs/layout.tsx
frontend/app/docs/offline-learning/page.tsx
frontend/app/docs/overview/page.tsx
frontend/app/docs/page.tsx
frontend/app/docs/quickstart/page.tsx
frontend/app/docs/sacagent/page.tsx
frontend/app/globals.css
frontend/app/layout.tsx
frontend/app/page.tsx
frontend/components.json
frontend/components/doc-layout.tsx
frontend/components/kokonutui/background-paths.tsx
frontend/components/theme-provider.tsx
frontend/components/ui/accordion.tsx
frontend/components/ui/alert-dialog.tsx
frontend/components/ui/alert.tsx
frontend/components/ui/aspect-ratio.tsx
frontend/components/ui/avatar.tsx
frontend/components/ui/badge.tsx
frontend/components/ui/breadcrumb.tsx
frontend/components/ui/button.tsx
frontend/components/ui/calendar.tsx
frontend/components/ui/card.tsx
frontend/components/ui/carousel.tsx
frontend/components/ui/chart.tsx
frontend/components/ui/checkbox.tsx
frontend/components/ui/collapsible.tsx
frontend/components/ui/command.tsx
frontend/components/ui/context-menu.tsx
frontend/components/ui/dialog.tsx
frontend/components/ui/drawer.tsx
frontend/components/ui/dropdown-menu.tsx
frontend/components/ui/form.tsx
frontend/components/ui/hover-card.tsx
frontend/components/ui/input-otp.tsx
frontend/components/ui/input.tsx
frontend/components/ui/label.tsx
frontend/components/ui/menubar.tsx
frontend/components/ui/navigation-menu.tsx
frontend/components/ui/pagination.tsx
frontend/components/ui/popover.tsx
frontend/components/ui/progress.tsx
frontend/components/ui/radio-group.tsx
frontend/components/ui/resizable.tsx
frontend/components/ui/scroll-area.tsx
frontend/components/ui/select.tsx
frontend/components/ui/separator.tsx
frontend/components/ui/sheet.tsx
frontend/components/ui/sidebar.tsx
frontend/components/ui/skeleton.tsx
frontend/components/ui/slider.tsx
frontend/components/ui/sonner.tsx
frontend/components/ui/switch.tsx
frontend/components/ui/table.tsx
frontend/components/ui/tabs.tsx
frontend/components/ui/textarea.tsx
frontend/components/ui/toast.tsx
frontend/components/ui/toaster.tsx
frontend/components/ui/toggle-group.tsx
frontend/components/ui/toggle.tsx
frontend/components/ui/tooltip.tsx
frontend/components/ui/use-mobile.tsx
frontend/components/ui/use-toast.ts
frontend/hooks/use-mobile.tsx
frontend/hooks/use-toast.ts
frontend/lib/utils.ts
frontend/next.config.mjs
frontend/package.json
frontend/postcss.config.mjs
frontend/styles/globals.css
frontend/tailwind.config.ts
frontend/tsconfig.json
README.md
regularized_q.py
test_agents.py
```

### Dependencies

- frontend/package.json: @emotion/is-prop-valid@latest, @hookform/resolvers@^3.9.1, @radix-ui/react-accordion@^1.2.2, @radix-ui/react-alert-dialog@^1.1.4, @radix-ui/react-aspect-ratio@^1.1.1, @radix-ui/react-avatar@^1.1.2, @radix-ui/react-checkbox@^1.1.3, @radix-ui/react-collapsible@^1.1.2, @radix-ui/react-context-menu@^2.2.4, @radix-ui/react-dialog@^1.1.4, @radix-ui/react-dropdown-menu@^2.1.4, @radix-ui/react-hover-card@^1.1.4, @radix-ui/react-label@^2.1.1, @radix-ui/react-menubar@^1.1.4, @radix-ui/react-navigation-menu@^1.2.3, @radix-ui/react-popover@^1.1.4, @radix-ui/react-progress@^1.1.1, @radix-ui/react-radio-group@^1.2.2, @radix-ui/react-scroll-area@^1.2.2, @radix-ui/react-select@^2.1.4, @radix-ui/react-separator@^1.1.1, @radix-ui/react-slider@^1.2.2, @radix-ui/react-slot@^1.1.1, @radix-ui/react-switch@^1.1.2, @radix-ui/react-tabs@^1.1.2, @radix-ui/react-toast@^1.2.4, @radix-ui/react-toggle@^1.1.1, @radix-ui/react-toggle-group@^1.1.1, @radix-ui/react-tooltip@^1.1.6, @types/node@^22, @types/react@^18, @types/react-dom@^18, autoprefixer@^10.4.20, class-variance-authority@^0.7.1, clsx@^2.1.1, cmdk@1.0.4, date-fns@4.1.0, embla-carousel-react@8.5.1, framer-motion@latest, input-otp@1.4.1, lucide-react@^0.454.0, next@14.2.16, next-themes@^0.4.4, postcss@^8, react@^18, react-day-picker@8.10.1, react-dom@^18, react-hook-form@^7.54.1, react-resizable-panels@^2.1.7, recharts@2.15.0, sonner@^1.7.1, tailwind-merge@^2.5.5, tailwindcss@^3.4.17, tailwindcss-animate@^1.0.7, typescript@^5, vaul@^0.9.6, zod@^3.24.1

### Recent commits (newest first)

- Update README.md
- added frontend
- library version
- base conformal + sac, testing if works
- Initial commit

## Key source files (fetched from GitHub, selected and truncated for size)

### frontend/package.json

```
{
  "name": "my-v0-project",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@hookform/resolvers": "^3.9.1",
    "@radix-ui/react-accordion": "^1.2.2",
    "@radix-ui/react-alert-dialog": "^1.1.4",
    "@radix-ui/react-aspect-ratio": "^1.1.1",
    "@radix-ui/react-avatar": "^1.1.2",
    "@radix-ui/react-checkbox": "^1.1.3",
    "@radix-ui/react-collapsible": "^1.1.2",
    "@radix-ui/react-context-menu": "^2.2.4",
    "@radix-ui/react-dialog": "^1.1.4",
    "@radix-ui/react-dropdown-menu": "^2.1.4",
    "@radix-ui/react-hover-card": "^1.1.4",
    "@radix-ui/react-label": "^2.1.1",
    "@radix-ui/react-menubar": "^1.1.4",
    "@radix-ui/react-navigation-menu": "^1.2.3",
    "@radix-ui/react-popover": "^1.1.4",
    "@radix-ui/react-progress": "^1.1.1",
    "@radix-ui/react-radio-group": "^1.2.2",
    "@radix-ui/react-scroll-area": "^1.2.2",
    "@radix-ui/react-select": "^2.1.4",
    "@radix-ui/react-separator": "^1.1.1",
    "@radix-ui/react-slider": "^1.2.2",
    "@radix-ui/react-slot": "^1.1.1",
    "@radix-ui/react-switch": "^1.1.2",
    "@radix-ui/react-tabs": "^1.1.2",
    "@radix-ui/react-toast": "^1.2.4",
    "@radix-ui/react-toggle": "^1.1.1",
    "@radix-ui/react-toggle-group": "^1.1.1",
    "@radix-ui/react-tooltip": "^1.1.6",
    "autoprefixer": "^10.4.20",
    "class-variance-authority": "^0.7.1",
    "clsx": "^2.1.1",
    "cmdk": "1.0.4",
    "date-fns": "4.1.0",
    "embla-carousel-react": "8.5.1",
    "input-otp": "1.4.1",
    "lucide-react": "^0.454.0",
    "next": "14.2.16",
    "next-themes": "^0.4.4",
    "react": "^18",
    "react-day-picker": "8.10.1",
    "react-dom": "^18",
    "react-hook-form": "^7.54.1",
    "react-resizable-panels": "^2.1.7",
    "recharts": "2.15.0",
    "sonner": "^1.7.1",
    "tailwind-merge": "^2.5.5",
    "tailwindcss-animate": "^1.0.7",
    "vaul": "^0.9.6",
    "zod": "^3.24.1",
    "@emotion/is-prop-valid": "latest",
    "framer-motion": "latest"
  },
  "devDependencies": {
    "@types/node": "^22",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "postcss": "^8",
    "tailwindcss": "^3.4.17",
    "typescript": "^5"
  }
}
```

### frontend/app/layout.tsx

```typescript
import type { Metadata } from 'next'
import './globals.css'

export const metadata: Metadata = {
  title: 'v0 App',
  description: 'Created with v0',
  generator: 'v0.dev',
}

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode
}>) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}

```

### frontend/app/page.tsx

```typescript
"use client"

import { useState, useEffect } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { Button } from "@/components/ui/button"
import { Github } from "lucide-react"
import Link from "next/link"

function StarryBackground() {
  const [hoveredStar, setHoveredStar] = useState<number | null>(null)
  const [stars, setStars] = useState<Array<{ id: number; x: number; y: number; size: number; delay: number }>>([])

  useEffect(() => {
    // Create 200 stars with random positions, sizes, and animation delays
    const newStars = Array.from({ length: 200 }, (_, i) => ({
      id: i,
      x: Math.random() * 100,
      y: Math.random() * 100,
      size: Math.random() * 0.15 + 0.05, // Sizes between 0.05 and 0.2
      delay: Math.random() * 3, // Random delay for twinkling effect
    }))
    setStars(newStars)
  }, [])

  return (
    <div className="absolute inset-0 pointer-events-none">
      <svg className="w-full h-full" viewBox="0 0 100 100">
        <defs>
          <radialGradient id="starGlow" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="white" stopOpacity="1" />
            <stop offset="100%" stopColor="white" stopOpacity="0" />
          </radialGradient>
        </defs>
        {stars.map((star) => (
          <g key={star.id}>
            <motion.circle
              cx={star.x}
              cy={star.y}
              r={star.size}
              fill="white"
              initial={{ opacity: 0.1 }}
              animate={{
                opacity: [0.2, 0.8, 0.2],
                scale: hoveredStar === star.id ? [1, 1.5, 1] : [1, 1.2, 1],
              }}
              transition={{
                duration: 2 + star.delay,
                repeat: Number.POSITIVE_INFINITY,
                ease: "easeInOut",
              }}
              onMouseEnter={() => setHoveredStar(star.id)}
              onMouseLeave={() => setHoveredStar(null)}
            />
            <AnimatePresence>
              {hoveredStar === star.id && (
                <motion.circle
                  cx={star.x}
                  cy={star.y}
                  r={star.size * 4}
                  fill="url(#starGlow)"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 0.5 }}
                  exit={{ opacity: 0 }}
                  transition={{ duration: 0.3 }}
                />
              )}
            </AnimatePresence>
          </g>
        ))}
      </svg>
    </div>
  )
}

export default function LandingPage() {
  const title = "RL-CP Fusion"
  const words = title.split(" ")

  return (
    <div className="relative min-h-screen w-full flex items-center justify-center overflow-hidden bg-[#0a0a0a]">
      <StarryBackground />

      <div className="relative z-10 container mx-auto px-4 md:px-6 text-center">
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 2 }}
          className="max-w-4xl mx-auto"
        >
          <h1 className="text-5xl sm:text-7xl md:text-8xl font-bold mb-8 tracking-tighter">
            {words.map((word, wordIndex) => (
              <span key={wordIndex} className="inline-block mr-4 last:mr-0">
                {word.split("").map((letter, letterIndex) => (
                  <motion.span
                    key={`${wordIndex}-${letterIndex}`}
                    initial={{ y: 100, opacity: 0 }}
                    animate={{ y: 0, opacity: 1 }}
                    transition={{
                      delay: wordIndex * 0.1 + letterIndex * 0.03,
                      type: "spring",
                      stiffness: 150,
                      damping: 25,
                    }}
                    className="inline-block text-transparent bg-clip-text bg-gradient-to-r from-white to-gray-300"
                  >
                    {letter}
                  </motion.span>
                ))}
              </span>
            ))}
          </h1>

          <motion.p
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8, delay: 0.5 }}
            className="text-xl sm:text-2xl text-gray-300 max-w-2xl mx-auto mb-8"
          >
            Offline Reinforcement Learning with Conformal Prediction
          </motion.p>

          <motion.p
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8, delay: 0.7 }}
            className="text-lg text-gray-400 max-w-3xl mx-auto mb-12"
          >
            Tackle real-world decision-making challenges with our innovative approach that combines the power of Offline
            Reinforcement Learning and the reliability of Conformal Prediction.
          </motion.p>

          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8, delay: 0.9 }}
            className="flex flex-col sm:flex-row gap-4 justify-center mb-16"
          >
            <div className="group relative">
              <div className="absolute -inset-0.5 bg-gradient-to-r from-white to-gray-400 rounded-2xl blur opacity-30 group-hover:opacity-60 transition duration-500"></div>
              <Button
                variant="ghost"
                className="relative rounded-[1.15rem] px-8 py-6 text-lg font-semibold bg-black/90 text-white 
                          transition-all duration-300 group-hover:-translate-y-1 border border-white/10"
                onClick={() => window.open("https://github.com/khushgx/cql", "_blank")}
              >
                <Github className="mr-2 h-5 w-5" />
                <span className="opacity-90 group-hover:opacity-100 transition-opacity">View on GitHub</span>
                <span className="ml-3 opacity-70 group-hover:opacity-100 group-hover:translate-x-1.5 transition-all duration-300">
                  →
                </span>
              </Button>
[truncated — 2587 more characters]
```

### frontend/app/docs/layout.tsx

```typescript
import type { Metadata } from "next"
import { Inter } from "next/font/google"
import "./globals.css"
import type React from "react" // Added import for React

const inter = Inter({ subsets: ["latin"] })

export const metadata: Metadata = {
  title: "RL-CP Fusion Documentation",
  description: "Documentation for the RL-CP Fusion library",
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className="dark">
      <body className={`${inter.className} min-h-screen bg-[#1a1a1a]`}>{children}</body>
    </html>
  )
}


```

### frontend/app/docs/page.tsx

```typescript
"use client"

import { useState, useEffect } from "react"
import { motion } from "framer-motion"
import Link from "next/link"
import { Search, ChevronLeft, Copy } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"

function StarryBackground() {
  const [stars, setStars] = useState<Array<{ id: number; x: number; y: number; size: number; delay: number }>>([])

  useEffect(() => {
    const newStars = Array.from({ length: 100 }, (_, i) => ({
      id: i,
      x: Math.random() * 100,
      y: Math.random() * 100,
      size: Math.random() * 0.1 + 0.05,
      delay: Math.random() * 3,
    }))
    setStars(newStars)
  }, [])

  return (
    <div className="fixed inset-0 pointer-events-none opacity-20">
      <svg className="w-full h-full" viewBox="0 0 100 100">
        {stars.map((star) => (
          <motion.circle
            key={star.id}
            cx={star.x}
            cy={star.y}
            r={star.size}
            fill="white"
            initial={{ opacity: 0.1 }}
            animate={{
              opacity: [0.2, 0.8, 0.2],
              scale: [1, 1.2, 1],
            }}
            transition={{
              duration: 2 + star.delay,
              repeat: Number.POSITIVE_INFINITY,
              ease: "easeInOut",
            }}
          />
        ))}
      </svg>
    </div>
  )
}

const sections = {
  "GET STARTED": [
    { title: "Overview", href: "/docs/overview" },
    { title: "Quickstart", href: "/docs/quickstart" },
    { title: "Installation", href: "/docs/installation" },
  ],
  "CORE CONCEPTS": [
    { title: "SACAgent", href: "/docs/sacagent" },
    { title: "Conformal Prediction", href: "/docs/conformal-prediction" },
    { title: "Offline Learning", href: "/docs/offline-learning" },
  ],
  "API REFERENCE": [
    { title: "SACAgent Class", href: "/docs/api/sacagent" },
    { title: "Configuration", href: "/docs/api/configuration" },
    { title: "Utilities", href: "/docs/api/utilities" },
  ],
}

export default function DocsPage() {
  const [searchQuery, setSearchQuery] = useState("")

  return (
    <div className="relative min-h-screen bg-[#1a1a1a] text-white">
      <StarryBackground />

      {/* Left Sidebar */}
      <div className="fixed top-0 left-0 h-screen w-64 bg-[#0a0a0a]/90 border-r border-white/10 overflow-y-auto">
        <div className="p-4">
          <Link href="/">
            <Button variant="ghost" className="mb-4 text-white/70 hover:text-white w-full justify-start">
              <ChevronLeft className="mr-2 h-4 w-4" />
              Back to Home
            </Button>
          </Link>

          <div className="relative mb-6">
            <Search className="absolute left-2 top-2.5 h-4 w-4 text-white/40" />
            <Input
              type="search"
              placeholder="Search documentation..."
              className="pl-8 bg-white/5 border-white/10 text-white/70 placeholder:text-white/40"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>

          <nav className="space-y-8">
            {Object.entries(sections).map(([category, items]) => (
              <div key={category}>
                <h2 className="text-xs font-semibold text-white/40 mb-2">{category}</h2>
                <ul className="space-y-1">
                  {items.map((item) => (
                    <li key={item.title}>
                      <Link
                        href={item.href}
                        className="block px-2 py-1.5 text-sm text-white/70 hover:text-white hover:bg-white/5 rounded-md"
                      >
                        {item.title}
                      </Link>
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </nav>
        </div>
      </div>

      {/* Main Content */}
      <div className="ml-64 mr-64 p-12">
        <div className="max-w-4xl">
          <div className="flex justify-between items-start mb-8">
            <div>
              <h1 className="text-4xl font-bold mb-4">SACAgent Class</h1>
              <p className="text-lg text-white/70">The main interface for working with the Conformal SAC agent.</p>
            </div>
            <Button variant="ghost" className="text-white/70 hover:text-white">
              <Copy className="mr-2 h-4 w-4" />
              Copy page
            </Button>
          </div>

          <div className="prose prose-invert max-w-none">
            <div className="rounded-lg bg-white/5 border border-white/10 p-4 mb-8">
              <p className="text-sm text-white/70">
                The SACAgent class provides a high-level wrapper for training and evaluating agents using the Conformal
                Soft Actor-Critic algorithm with offline datasets.
              </p>
            </div>

            <h2 className="text-2xl font-bold mt-12 mb-4">Initialization</h2>
            <p className="mb-4">Create a new SACAgent instance with the following parameters:</p>

            <div className="bg-[#0a0a0a] rounded-lg p-4 mb-6">
              <pre className="text-sm text-white/90">
                <code>{`from conformal_sac.agent_wrapper import SACAgent

agent = SACAgent(
    env_name="halfcheetah-medium-expert",
    offline=True,
    iteration=100000,
    seed=42,
    learning_rate=3e-4,
    gamma=0.99,
    tau=0.005,
    batch_size=256,
    log_interval=2000,
    alpha_q=100,
    q_alpha_update_freq=50
)`}</code>
              </pre>
            </div>

            <h3 className="text-xl font-semibold mt-8 mb-4">Parameters</h3>
            <ul className="space-y-4">
              <li>
                <code className="bg-white/10 px-2 py-1 rounded text-sm">env_name</code>
                <span className="text-white/70 ml-2">string</span>
                <p className="mt-1 text-white/70">Name of the Gym (or D4RL) environment.</p>
              </li>
              <li>
             
[truncated — 2798 more characters]
```

### frontend/app/docs/installation/page.tsx

```typescript
"use client"
import { Copy } from "lucide-react"
import { Button } from "@/components/ui/button"
import DocLayout from "@/components/doc-layout"

export default function InstallationPage() {
  return (
    <DocLayout>
      <div className="max-w-4xl">
        <div className="flex justify-between items-start mb-8">
          <div>
            <h1 className="text-4xl font-bold mb-4">Installation</h1>
            <p className="text-lg text-white/70">Set up RL-CP Fusion in your environment</p>
          </div>
          <Button variant="ghost" className="text-white/70 hover:text-white">
            <Copy className="mr-2 h-4 w-4" />
            Copy page
          </Button>
        </div>

        <div className="prose prose-invert max-w-none">
          <div className="rounded-lg bg-white/5 border border-white/10 p-4 mb-8">
            <p className="text-sm text-white/70">Follow these steps to install RL-CP Fusion and its dependencies.</p>
          </div>

          <h2 className="text-2xl font-bold mt-12 mb-4">System Requirements</h2>
          <ul className="space-y-2 list-disc list-inside mb-8">
            <li className="text-white/70">Python 3.7 or higher</li>
            <li className="text-white/70">CUDA-compatible GPU (recommended)</li>
            <li className="text-white/70">64-bit operating system</li>
          </ul>

          <h2 className="text-2xl font-bold mt-12 mb-4">Installing Dependencies</h2>
          <p className="mb-4">First, install PyTorch with CUDA support:</p>
          <div className="bg-[#0a0a0a] rounded-lg p-4 mb-6">
            <pre className="text-sm text-white/90">
              <code>{`pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118`}</code>
            </pre>
          </div>

          <p className="mb-4">Install other required packages:</p>
          <div className="bg-[#0a0a0a] rounded-lg p-4 mb-6">
            <pre className="text-sm text-white/90">
              <code>{`pip install gym d4rl numpy tensorboardX`}</code>
            </pre>
          </div>

          <h2 className="text-2xl font-bold mt-12 mb-4">Installing RL-CP Fusion</h2>
          <p className="mb-4">Clone the repository:</p>
          <div className="bg-[#0a0a0a] rounded-lg p-4 mb-6">
            <pre className="text-sm text-white/90">
              <code>{`git clone https://github.com/yourusername/rl-cp-fusion.git
cd rl-cp-fusion`}</code>
            </pre>
          </div>

          <p className="mb-4">Install the package:</p>
          <div className="bg-[#0a0a0a] rounded-lg p-4 mb-6">
            <pre className="text-sm text-white/90">
              <code>{`pip install -e .`}</code>
            </pre>
          </div>

          <h2 className="text-2xl font-bold mt-12 mb-4">Verifying Installation</h2>
          <p className="mb-4">Run this simple test to verify the installation:</p>
          <div className="bg-[#0a0a0a] rounded-lg p-4 mb-6">
            <pre className="text-sm text-white/90">
              <code>{`python -c "from conformal_sac.agent_wrapper import SACAgent; print('Installation successful!')"`}</code>
            </pre>
          </div>

          <h2 className="text-2xl font-bold mt-12 mb-4">Common Issues</h2>

          <h3 className="text-xl font-semibold mt-8 mb-4">CUDA Issues</h3>
          <p className="mb-4">If you encounter CUDA-related errors, verify your CUDA installation:</p>
          <div className="bg-[#0a0a0a] rounded-lg p-4 mb-6">
            <pre className="text-sm text-white/90">
              <code>{`python -c "import torch; print(torch.cuda.is_available())"`}</code>
            </pre>
          </div>

          <h3 className="text-xl font-semibold mt-8 mb-4">D4RL Dataset Access</h3>
          <p className="mb-4">
            If you have trouble accessing D4RL datasets, make sure you have the correct permissions:
          </p>
          <div className="bg-[#0a0a0a] rounded-lg p-4 mb-6">
            <pre className="text-sm text-white/90">
              <code>{`python -c "import d4rl; import gym; env = gym.make('halfcheetah-medium-v2')"`}</code>
            </pre>
          </div>

          <h2 className="text-2xl font-bold mt-12 mb-4">Next Steps</h2>
          <p className="mb-4">After installation, you can:</p>
          <ul className="space-y-2 list-disc list-inside">
            <li className="text-white/70">
              Follow the{" "}
              <a href="/docs/quickstart" className="text-blue-400 hover:text-blue-300">
                Quickstart Guide
              </a>
            </li>
            <li className="text-white/70">
              Read about{" "}
              <a href="/docs/sacagent" className="text-blue-400 hover:text-blue-300">
                SACAgent
              </a>
            </li>
            <li className="text-white/70">
              Explore{" "}
              <a href="/docs/api/configuration" className="text-blue-400 hover:text-blue-300">
                Configuration Options
              </a>
            </li>
          </ul>
        </div>
      </div>
    </DocLayout>
  )
}


```

### frontend/app/docs/quickstart/page.tsx

```typescript
"use client"
import { Copy } from "lucide-react"
import { Button } from "@/components/ui/button"
import DocLayout from "@/components/doc-layout"

export default function QuickstartPage() {
  return (
    <DocLayout>
      <div className="max-w-4xl">
        <div className="flex justify-between items-start mb-8">
          <div>
            <h1 className="text-4xl font-bold mb-4">Quickstart</h1>
            <p className="text-lg text-white/70">Get started with RL-CP Fusion in minutes</p>
          </div>
          <Button variant="ghost" className="text-white/70 hover:text-white">
            <Copy className="mr-2 h-4 w-4" />
            Copy page
          </Button>
        </div>

        <div className="prose prose-invert max-w-none">
          <div className="rounded-lg bg-white/5 border border-white/10 p-4 mb-8">
            <p className="text-sm text-white/70">
              This guide will help you train your first agent using RL-CP Fusion with a D4RL dataset.
            </p>
          </div>

          <h2 className="text-2xl font-bold mt-12 mb-4">Prerequisites</h2>
          <p className="mb-4">Before you begin, make sure you have:</p>
          <ul className="space-y-2 list-disc list-inside mb-8">
            <li className="text-white/70">Python 3.7 or higher installed</li>
            <li className="text-white/70">pip package manager</li>
            <li className="text-white/70">Basic understanding of reinforcement learning concepts</li>
          </ul>

          <h2 className="text-2xl font-bold mt-12 mb-4">Installation</h2>
          <p className="mb-4">First, install the required packages:</p>
          <div className="bg-[#0a0a0a] rounded-lg p-4 mb-6">
            <pre className="text-sm text-white/90">
              <code>{`pip install torch gym d4rl numpy tensorboardX`}</code>
            </pre>
          </div>

          <h2 className="text-2xl font-bold mt-12 mb-4">Training Your First Agent</h2>
          <p className="mb-4">Here's a complete example to train an agent on the HalfCheetah environment:</p>
          <div className="bg-[#0a0a0a] rounded-lg p-4 mb-6">
            <pre className="text-sm text-white/90">
              <code>{`from conformal_sac.agent_wrapper import SACAgent

# Initialize the agent
agent = SACAgent(
    env_name="halfcheetah-medium-v2",
    offline=True,
    iteration=100000,
    seed=42,
    learning_rate=3e-4,
    gamma=0.99,
    tau=0.005,
    batch_size=256,
    log_interval=2000,
    alpha_q=100,
    q_alpha_update_freq=50
)

# Train the agent
agent.train()

# Evaluate the trained agent
score = agent.evaluate(eval_episodes=10)
print(f"Final evaluation score: {score}")`}</code>
            </pre>
          </div>

          <h2 className="text-2xl font-bold mt-12 mb-4">Understanding the Code</h2>
          <p className="mb-4">Let's break down what's happening in the code above:</p>

          <h3 className="text-xl font-semibold mt-8 mb-4">1. Agent Initialization</h3>
          <p className="mb-4">We create a new SACAgent instance with specific hyperparameters:</p>
          <ul className="space-y-2 list-disc list-inside mb-6">
            <li className="text-white/70">
              <code>env_name</code>: The D4RL environment to use
            </li>
            <li className="text-white/70">
              <code>offline</code>: Set to True for offline learning
            </li>
            <li className="text-white/70">
              <code>iteration</code>: Number of training iterations
            </li>
            <li className="text-white/70">
              <code>seed</code>: Random seed for reproducibility
            </li>
            <li className="text-white/70">Various hyperparameters for the SAC algorithm</li>
          </ul>

          <h3 className="text-xl font-semibold mt-8 mb-4">2. Training</h3>
          <p className="mb-4">
            The <code>train()</code> method:
          </p>
          <ul className="space-y-2 list-disc list-inside mb-6">
            <li className="text-white/70">Loads the offline dataset</li>
            <li className="text-white/70">Performs training iterations</li>
            <li className="text-white/70">Updates the agent's policy</li>
            <li className="text-white/70">Periodically evaluates performance</li>
          </ul>

          <h3 className="text-xl font-semibold mt-8 mb-4">3. Evaluation</h3>
          <p className="mb-4">
            The <code>evaluate()</code> method runs the trained policy for multiple episodes and returns the average
            reward.
          </p>

          <h2 className="text-2xl font-bold mt-12 mb-4">Monitoring Training</h2>
          <p className="mb-4">You can monitor the training progress using TensorBoard:</p>
          <div className="bg-[#0a0a0a] rounded-lg p-4 mb-6">
            <pre className="text-sm text-white/90">
              <code>{`tensorboard --logdir ./exp-SAC_dual_Q_network`}</code>
            </pre>
          </div>

          <h2 className="text-2xl font-bold mt-12 mb-4">Next Steps</h2>
          <p className="mb-4">Now that you've trained your first agent, you can:</p>
          <ul className="space-y-2 list-disc list-inside">
            <li className="text-white/70">
              Learn about{" "}
              <a href="/docs/conformal-prediction" className="text-blue-400 hover:text-blue-300">
                Conformal Prediction
              </a>
            </li>
            <li className="text-white/70">
              Understand{" "}
              <a href="/docs/offline-learning" className="text-blue-400 hover:text-blue-300">
                Offline Learning
              </a>
            </li>
            <li className="text-white/70">
              Explore the{" "}
              <a href="/docs/api/sacagent" className="text-blue-400 hover:text-blue-300">
                API Reference
              </a>
            </li>
          </ul>
        </div>
      </div>
    </DocLayout>
  )
}


```

### frontend/app/docs/conformal-q-learning/page.tsx

```typescript
"use client"

import { Copy } from "lucide-react"
import { Button } from "@/components/ui/button"
import DocLayout from "@/components/doc-layout"

export default function ConformalQLearningPage() {
  return (
    <DocLayout>
      <div className="max-w-4xl">
        <div className="flex justify-between items-start mb-8">
          <div>
            <h1 className="text-4xl font-bold mb-4">Conformal Q-Learning</h1>
            <p className="text-lg text-white/70">Understanding the core component of RL-CP Fusion</p>
          </div>
          <Button variant="ghost" className="text-white/70 hover:text-white">
            <Copy className="mr-2 h-4 w-4" />
            Copy page
          </Button>
        </div>

        <div className="prose prose-invert max-w-none">
          <div className="rounded-lg bg-white/5 border border-white/10 p-4 mb-8">
            <p className="text-sm text-white/70">
              Conformal Q-Learning integrates conformal prediction into an actor-critic framework to address
              extrapolation error in offline reinforcement learning.
            </p>
          </div>

          <h2 className="text-2xl font-bold mt-12 mb-4">What is Conformal Q-Learning?</h2>
          <p className="mb-6">
            Conformal Q-Learning is a novel approach that combines conformal prediction with actor-critic methods to
            provide finite-sample uncertainty guarantees for Q-value estimates in offline reinforcement learning. It
            constructs prediction intervals around learned Q-values to ensure that true values lie within these
            intervals with high probability, using interval width as a regularizer to mitigate overestimation and
            stabilize policy learning.
          </p>

          <h2 className="text-2xl font-bold mt-12 mb-4">Key Components</h2>

          <h3 className="text-xl font-semibold mt-8 mb-4">1. Conformal Prediction Integration</h3>
          <p className="mb-6">
            Conformal prediction is used to generate uncertainty estimates for Q-values. This is crucial in offline RL
            to avoid overconfident estimates for out-of-distribution actions. The algorithm maintains a calibration set
            and periodically updates conformal intervals to ensure reliable uncertainty quantification.
          </p>

          <h3 className="text-xl font-semibold mt-8 mb-4">2. Actor-Critic Framework</h3>
          <p className="mb-6">
            Conformal Q-Learning builds upon the actor-critic architecture, where a critic (Q-function) estimates
            action-values and an actor (policy) selects actions. The conformal intervals are incorporated into both the
            critic updates and policy improvement steps.
          </p>

          <h3 className="text-xl font-semibold mt-8 mb-4">3. Offline Learning Mechanism</h3>
          <p className="mb-6">
            The algorithm is designed to learn from static datasets without interacting with the environment during
            training. It uses techniques like conformal regularization to mitigate the challenges of offline RL, such as
            extrapolation error and distributional shift.
          </p>

          <h2 className="text-2xl font-bold mt-12 mb-4">How Conformal Q-Learning Works</h2>

          <h3 className="text-xl font-semibold mt-8 mb-4">1. Initialization</h3>
          <p className="mb-6">
            The algorithm initializes a Q-network, policy network, and a calibration dataset. It also sets up learning
            rates and thresholds for conformal prediction.
          </p>

          <h3 className="text-xl font-semibold mt-8 mb-4">2. Training Loop</h3>
          <p className="mb-6">During training, Conformal Q-Learning:</p>
          <ul className="list-disc list-inside mb-6">
            <li>Samples batches from the offline dataset</li>
            <li>Calibrates conformal intervals using the calibration set</li>
            <li>Updates the Q-network (critic) using the Bellman equation and conformal regularization</li>
            <li>Updates the policy network (actor) incorporating the conformal intervals</li>
          </ul>

          <h3 className="text-xl font-semibold mt-8 mb-4">3. Conformal Interval Calibration</h3>
          <p className="mb-6">
            The algorithm computes nonconformity scores and determines the conformal threshold (q_α) based on the
            calibration dataset. This threshold is used to construct prediction intervals for Q-values.
          </p>

          <h2 className="text-2xl font-bold mt-12 mb-4">Advantages of Conformal Q-Learning</h2>
          <ul className="list-disc list-inside mb-6">
            <li>Provides uncertainty quantification for Q-value estimates</li>
            <li>Mitigates overestimation bias in offline reinforcement learning</li>
            <li>Improves stability and reliability of learned policies</li>
            <li>Offers theoretical guarantees on the coverage of prediction intervals</li>
          </ul>

          <h2 className="text-2xl font-bold mt-12 mb-4">Conclusion</h2>
          <p className="mb-6">
            Conformal Q-Learning represents a significant advancement in offline reinforcement learning by providing
            theoretically grounded uncertainty estimates. By integrating conformal prediction into the actor-critic
            framework, it addresses key challenges in offline RL, such as extrapolation error and policy stability. The
            method's success in both theoretical analysis and empirical evaluations makes it a promising approach for
            reliable offline RL in safety-critical and resource-constrained environments.
          </p>

          <div className="rounded-lg bg-white/5 border border-white/10 p-4 mt-8">
            <p className="text-sm text-white/70">
              Next, learn about{" "}
              <a href="/docs/conformal-prediction" className="text-blue-400 hover:text-blue-300">
                Conformal Prediction
       
[truncated — 177 more characters]
```

### test_agents.py

```python
# run_agent.py

from conformal_agent.agent_wrapper import SACAgent

def main():
    agent = SACAgent(
        env_name="halfcheetah-medium-expert",
        offline=True,
        iteration=10,  #
        seed=42,
        learning_rate=3e-4,
        gamma=0.99,
        tau=0.005,
        batch_size=256,
        log_interval=5,
        alpha_q=100,
        q_alpha_update_freq=50
    )

    agent.train()

    score = agent.evaluate(eval_episodes=2)
    print(f"Final evaluation score: {score}")

if __name__ == "__main__":
    main()

```

### frontend/tailwind.config.ts

```typescript
import type { Config } from "tailwindcss";

const config: Config = {
    darkMode: ["class"],
    content: [
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
    "*.{js,ts,jsx,tsx,mdx}"
  ],
  theme: {
  	extend: {
  		colors: {
  			background: 'hsl(var(--background))',
  			foreground: 'hsl(var(--foreground))',
  			card: {
  				DEFAULT: 'hsl(var(--card))',
  				foreground: 'hsl(var(--card-foreground))'
  			},
  			popover: {
  				DEFAULT: 'hsl(var(--popover))',
  				foreground: 'hsl(var(--popover-foreground))'
  			},
  			primary: {
  				DEFAULT: 'hsl(var(--primary))',
  				foreground: 'hsl(var(--primary-foreground))'
  			},
  			secondary: {
  				DEFAULT: 'hsl(var(--secondary))',
  				foreground: 'hsl(var(--secondary-foreground))'
  			},
  			muted: {
  				DEFAULT: 'hsl(var(--muted))',
  				foreground: 'hsl(var(--muted-foreground))'
  			},
  			accent: {
  				DEFAULT: 'hsl(var(--accent))',
  				foreground: 'hsl(var(--accent-foreground))'
  			},
  			destructive: {
  				DEFAULT: 'hsl(var(--destructive))',
  				foreground: 'hsl(var(--destructive-foreground))'
  			},
  			border: 'hsl(var(--border))',
  			input: 'hsl(var(--input))',
  			ring: 'hsl(var(--ring))',
  			chart: {
  				'1': 'hsl(var(--chart-1))',
  				'2': 'hsl(var(--chart-2))',
  				'3': 'hsl(var(--chart-3))',
  				'4': 'hsl(var(--chart-4))',
  				'5': 'hsl(var(--chart-5))'
  			},
  			sidebar: {
  				DEFAULT: 'hsl(var(--sidebar-background))',
  				foreground: 'hsl(var(--sidebar-foreground))',
  				primary: 'hsl(var(--sidebar-primary))',
  				'primary-foreground': 'hsl(var(--sidebar-primary-foreground))',
  				accent: 'hsl(var(--sidebar-accent))',
  				'accent-foreground': 'hsl(var(--sidebar-accent-foreground))',
  				border: 'hsl(var(--sidebar-border))',
  				ring: 'hsl(var(--sidebar-ring))'
  			}
  		},
  		borderRadius: {
  			lg: 'var(--radius)',
  			md: 'calc(var(--radius) - 2px)',
  			sm: 'calc(var(--radius) - 4px)'
  		},
  		keyframes: {
  			'accordion-down': {
  				from: {
  					height: '0'
  				},
  				to: {
  					height: 'var(--radix-accordion-content-height)'
  				}
  			},
  			'accordion-up': {
  				from: {
  					height: 'var(--radix-accordion-content-height)'
  				},
  				to: {
  					height: '0'
  				}
  			}
  		},
  		animation: {
  			'accordion-down': 'accordion-down 0.2s ease-out',
  			'accordion-up': 'accordion-up 0.2s ease-out'
  		}
  	}
  },
  plugins: [require("tailwindcss-animate")],
};
export default config;

```

[69 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]