{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "gpuType": "T4" }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" }, "accelerator": "GPU" }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "=============================================================================\n", "FLAN-T5-Small Fine-Tuning for Task Decomposition (M6)\n", "=============================================================================\n", "Workflow360 FYP — AI Module Training Notebook\n", "\n", "This script fine-tunes google/flan-t5-small on a software project management\n", "task decomposition dataset. Each training example teaches the model to break\n", "a parent task into structured subtasks.\n", "\n", "Designed to run end-to-end on Google Colab free tier (T4 GPU, ~12 GB RAM).\n", "Expected training time: 45-90 minutes.\n", "\n", "To use as a Colab notebook:\n", " 1. Upload this file to Colab\n", " 2. Or copy-paste sections into cells (delimited by # SECTION comments)\n", " 3. Sections marked # MARKDOWN: are explanatory text cells\n", "\n", "Usage:\n", " python train_decomposition.py # local run\n", " # Or run cell-by-cell in Google Colab\n", "\n", "# FLAN-T5 Fine-Tuning for Task Decomposition\n", "\n", "This notebook fine-tunes **FLAN-T5-small** (77M params) to decompose\n", "software project management tasks into structured subtasks.\n", "\n", "**Model:** google/flan-t5-small\n", "**Dataset:** 3000-5000 synthetic PM task decomposition examples\n", "**Target metric:** ROUGE-L > 0.35\n", "**Hardware:** Google Colab T4 GPU (free tier)\n", "**Training time:** ~45-90 minutes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Setup & Dependencies\n", "Install required packages. These are pre-installed on Colab except for\n", "`rouge_score` and `accelerate`. Running `pip install` is idempotent." ] }, { "cell_type": "code", "metadata": {}, "source": [ "# ============================================================================\n", "# SECTION 1: Setup & Dependencies\n", "# ============================================================================\n", "\n", "import subprocess\n", "import sys\n", "\n", "def install(package):\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", package])\n", "\n", "install(\"transformers>=4.41.0\")\n", "install(\"datasets>=2.19.0\")\n", "install(\"torch>=2.3.0\")\n", "install(\"accelerate>=0.30.0\")\n", "install(\"evaluate>=0.4.0\")\n", "install(\"rouge_score>=0.1.2\")\n", "install(\"sentencepiece>=0.2.0\")\n", "\n", "import os\n", "import json\n", "import random\n", "import warnings\n", "from pathlib import Path\n", "\n", "import numpy as np\n", "import torch\n", "import evaluate\n", "from datasets import Dataset, DatasetDict\n", "from transformers import (\n", " T5Tokenizer,\n", " T5ForConditionalGeneration,\n", " Seq2SeqTrainer,\n", " Seq2SeqTrainingArguments,\n", " DataCollatorForSeq2Seq,\n", " EarlyStoppingCallback,\n", ")\n", "\n", "warnings.filterwarnings(\"ignore\", category=FutureWarning)\n", "\n", "# Reproducibility\n", "SEED = 42\n", "random.seed(SEED)\n", "np.random.seed(SEED)\n", "torch.manual_seed(SEED)\n", "\n", "# Device\n", "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "print(f\"Using device: {device}\")\n", "if device == \"cuda\":\n", " print(f\"GPU: {torch.cuda.get_device_name(0)}\")\n", " print(f\"Memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Dataset Loading\n", "\n", "We use a two-part approach:\n", "1. **Structural patterns** from a public HuggingFace dataset to teach the\n", " model structured text generation\n", "2. **Synthetic PM data** (Section 3) that directly targets our decomposition\n", " format\n", "\n", "The synthetic data is the primary training signal. The structural patterns\n", "dataset helps the model learn to produce well-formatted multi-line output." ] }, { "cell_type": "code", "metadata": {}, "source": [ "# ============================================================================\n", "# SECTION 2: Dataset Loading\n", "# ============================================================================\n", "\n", "print(\"\\n\" + \"=\"*60)\n", "print(\"SECTION 2: Loading structural pattern data\")\n", "print(\"=\"*60)\n", "\n", "from datasets import load_dataset\n", "\n", "# Load a small slice of structured text generation data for format learning.\n", "# We only need ~500 examples from this — the synthetic data is the main dataset.\n", "try:\n", " raw_infill = load_dataset(\"sander-wood/text-infilling\", split=\"train\", streaming=True)\n", " structural_examples = []\n", " for i, example in enumerate(raw_infill):\n", " if i >= 500:\n", " break\n", " # Adapt to our format: teach the model to produce structured multi-line output\n", " text = example.get(\"text\", \"\") or \"\"\n", " if len(text) > 50 and len(text) < 1000:\n", " # Create a decomposition-style example from structured text\n", " lines = [l.strip() for l in text.split(\"\\n\") if l.strip()]\n", " if len(lines) >= 3:\n", " input_text = (\n", " \"Decompose this software task into subtasks:\\n\"\n", " f\"Task: {lines[0][:100]}\\n\"\n", " f\"Description: Implement the following components\\n\"\n", " f\"Priority: medium\\n\"\n", " )\n", " output_lines = []\n", " for j, line in enumerate(lines[1:5], 1):\n", " output_lines.append(\n", " f\"SUBTASK_{j}: {line[:80]} | PRIORITY: medium | \"\n", " f\"POINTS: {random.choice([1,2,3,5])} | \"\n", " f\"DAYS: {random.choice([0.5, 1.0, 1.5, 2.0])} | \"\n", " f\"TAGS: general\"\n", " )\n", " if output_lines:\n", " structural_examples.append({\n", " \"input_text\": input_text,\n", " \"target_text\": \"\\n\".join(output_lines),\n", " })\n", " print(f\"Loaded {len(structural_examples)} structural pattern examples\")\n", "except Exception as e:\n", " print(f\"Could not load structural dataset ({e}) — using synthetic data only\")\n", " structural_examples = []" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Synthetic Data Generation\n", "\n", "We generate 2000+ training examples covering 6 categories of software\n", "project management tasks. Each example is an (input, output) pair where:\n", "\n", "- **Input:** Task title + description + priority + context\n", "- **Output:** Structured subtask list in a parseable format\n", "\n", "The format uses `SUBTASK_N: title | PRIORITY: p | POINTS: n | DAYS: n | TAGS: t1,t2`\n", "so the AI server can reliably parse model output back into structured data." ] }, { "cell_type": "code", "metadata": {}, "source": [ "# ============================================================================\n", "# SECTION 3: Synthetic Data Generation\n", "# ============================================================================\n", "\n", "print(\"\\n\" + \"=\"*60)\n", "print(\"SECTION 3: Generating synthetic PM decomposition data\")\n", "print(\"=\"*60)\n", "\n", "# --- Task templates per category ---\n", "\n", "FRONTEND_TASKS = [\n", " {\n", " \"title\": \"Build user dashboard page\",\n", " \"description\": \"Create a responsive dashboard showing project statistics, recent tasks, and team activity. Include charts for sprint burndown and velocity.\",\n", " \"priority\": \"high\",\n", " \"context\": \"React/Next.js project with Tailwind CSS and Recharts\",\n", " \"subtasks\": [\n", " (\"Design dashboard layout and component hierarchy\", \"high\", 3, 1.0, \"frontend,design\"),\n", " (\"Build statistics cards component\", \"medium\", 2, 0.5, \"frontend,ui\"),\n", " (\"Implement sprint burndown chart\", \"high\", 5, 2.0, \"frontend,charts\"),\n", " (\"Add velocity trend chart\", \"medium\", 3, 1.5, \"frontend,charts\"),\n", " (\"Create recent tasks feed widget\", \"medium\", 3, 1.0, \"frontend,ui\"),\n", " (\"Add responsive breakpoints and mobile layout\", \"low\", 2, 0.5, \"frontend,responsive\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Implement task card drag-and-drop\",\n", " \"description\": \"Add drag-and-drop functionality to the Kanban board. Tasks should be draggable between status columns with smooth animations.\",\n", " \"priority\": \"high\",\n", " \"context\": \"Using DnD Kit library in React\",\n", " \"subtasks\": [\n", " (\"Set up DnD Kit context and providers\", \"high\", 2, 0.5, \"frontend,dnd\"),\n", " (\"Make task cards draggable with drag handles\", \"high\", 3, 1.0, \"frontend,dnd\"),\n", " (\"Implement droppable status columns\", \"high\", 3, 1.0, \"frontend,dnd\"),\n", " (\"Add drag overlay with card preview\", \"medium\", 2, 0.5, \"frontend,ui\"),\n", " (\"Handle state update on drop\", \"high\", 3, 1.0, \"frontend,state\"),\n", " (\"Add smooth transition animations\", \"low\", 2, 0.5, \"frontend,animation\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Create notification center component\",\n", " \"description\": \"Build a dropdown notification center showing unread notifications, with real-time updates and mark-as-read functionality.\",\n", " \"priority\": \"medium\",\n", " \"context\": \"Next.js app with Supabase realtime subscriptions\",\n", " \"subtasks\": [\n", " (\"Design notification dropdown UI\", \"medium\", 2, 0.5, \"frontend,design\"),\n", " (\"Build notification list with virtual scrolling\", \"medium\", 3, 1.5, \"frontend,ui\"),\n", " (\"Add real-time subscription for new notifications\", \"high\", 3, 1.0, \"frontend,realtime\"),\n", " (\"Implement mark-as-read and bulk actions\", \"medium\", 2, 1.0, \"frontend,ui\"),\n", " (\"Add notification badge counter\", \"low\", 1, 0.5, \"frontend,ui\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Build settings page with form validation\",\n", " \"description\": \"Create a multi-tab settings page for user profile, notification preferences, and organization settings with proper form validation.\",\n", " \"priority\": \"medium\",\n", " \"context\": \"React Hook Form + Zod validation\",\n", " \"subtasks\": [\n", " (\"Create settings page layout with tabs\", \"medium\", 2, 0.5, \"frontend,ui\"),\n", " (\"Build profile settings form with avatar upload\", \"medium\", 3, 1.5, \"frontend,forms\"),\n", " (\"Add notification preferences toggle form\", \"low\", 2, 1.0, \"frontend,forms\"),\n", " (\"Implement organization settings panel\", \"medium\", 3, 1.5, \"frontend,forms\"),\n", " (\"Add Zod validation schemas for all forms\", \"medium\", 2, 1.0, \"frontend,validation\"),\n", " (\"Connect forms to API endpoints\", \"medium\", 2, 1.0, \"frontend,api\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Implement search and filter for task list\",\n", " \"description\": \"Add a search bar with auto-complete and advanced filters (status, priority, assignee, date range) for the task list view.\",\n", " \"priority\": \"medium\",\n", " \"context\": \"Task list uses server-side pagination with Supabase\",\n", " \"subtasks\": [\n", " (\"Build search input with debounced query\", \"medium\", 2, 0.5, \"frontend,search\"),\n", " (\"Add filter dropdown for status and priority\", \"medium\", 3, 1.0, \"frontend,ui\"),\n", " (\"Implement assignee filter with member selector\", \"medium\", 3, 1.0, \"frontend,ui\"),\n", " (\"Add date range picker for due date filter\", \"medium\", 2, 1.0, \"frontend,ui\"),\n", " (\"Connect filters to Supabase query params\", \"high\", 3, 1.0, \"frontend,api\"),\n", " (\"Add clear filters and save filter presets\", \"low\", 2, 1.0, \"frontend,ui\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Create onboarding flow for new users\",\n", " \"description\": \"Build a multi-step onboarding wizard that guides new users through profile setup, creating or joining an organization, and setting up their first project.\",\n", " \"priority\": \"high\",\n", " \"context\": \"Next.js app with Supabase Auth\",\n", " \"subtasks\": [\n", " (\"Design stepper UI for onboarding wizard\", \"medium\", 2, 0.5, \"frontend,design\"),\n", " (\"Build profile setup step with avatar and bio\", \"medium\", 3, 1.0, \"frontend,forms\"),\n", " (\"Create organization join/create step\", \"high\", 5, 2.0, \"frontend,auth\"),\n", " (\"Add first project creation step\", \"medium\", 3, 1.5, \"frontend,forms\"),\n", " (\"Implement progress persistence and skip logic\", \"medium\", 2, 1.0, \"frontend,state\"),\n", " (\"Add completion celebration screen\", \"low\", 1, 0.5, \"frontend,ui\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Build analytics chart components\",\n", " \"description\": \"Create reusable chart components for project analytics including burn-down, velocity, cumulative flow, and member contribution charts.\",\n", " \"priority\": \"medium\",\n", " \"context\": \"Using Recharts library\",\n", " \"subtasks\": [\n", " (\"Create base chart wrapper with common styling\", \"medium\", 2, 0.5, \"frontend,charts\"),\n", " (\"Build burn-down chart with ideal line overlay\", \"high\", 3, 1.5, \"frontend,charts\"),\n", " (\"Implement velocity bar chart by sprint\", \"medium\", 3, 1.0, \"frontend,charts\"),\n", " (\"Add cumulative flow diagram\", \"medium\", 5, 2.0, \"frontend,charts\"),\n", " (\"Create member contribution pie chart\", \"low\", 2, 1.0, \"frontend,charts\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Implement dark mode toggle\",\n", " \"description\": \"Add system-wide dark mode support with a toggle in the header. Persist user preference and respect system setting on first visit.\",\n", " \"priority\": \"low\",\n", " \"context\": \"Tailwind CSS with class-based dark mode\",\n", " \"subtasks\": [\n", " (\"Set up Tailwind dark mode config and CSS variables\", \"medium\", 2, 0.5, \"frontend,styling\"),\n", " (\"Build theme toggle button in header\", \"low\", 1, 0.5, \"frontend,ui\"),\n", " (\"Add theme persistence to localStorage\", \"low\", 1, 0.5, \"frontend,state\"),\n", " (\"Update all component styles for dark variants\", \"medium\", 5, 2.0, \"frontend,styling\"),\n", " (\"Detect system preference on first visit\", \"low\", 1, 0.5, \"frontend,ui\"),\n", " ],\n", " },\n", "]\n", "\n", "BACKEND_TASKS = [\n", " {\n", " \"title\": \"Build REST API for task CRUD\",\n", " \"description\": \"Create API endpoints for creating, reading, updating, and deleting tasks. Include proper validation, error handling, and authorization checks.\",\n", " \"priority\": \"high\",\n", " \"context\": \"Next.js API routes with Supabase, Row Level Security enabled\",\n", " \"subtasks\": [\n", " (\"Design API route structure and request schemas\", \"high\", 2, 0.5, \"backend,api\"),\n", " (\"Implement POST /api/tasks for task creation\", \"high\", 3, 1.0, \"backend,api\"),\n", " (\"Implement GET /api/tasks with pagination and filters\", \"high\", 3, 1.0, \"backend,api\"),\n", " (\"Implement PATCH /api/tasks/[id] for updates\", \"medium\", 2, 1.0, \"backend,api\"),\n", " (\"Implement DELETE /api/tasks/[id] with soft delete\", \"medium\", 2, 0.5, \"backend,api\"),\n", " (\"Add input validation with Zod schemas\", \"medium\", 2, 1.0, \"backend,validation\"),\n", " (\"Write error handling middleware\", \"medium\", 2, 0.5, \"backend,api\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Implement user authentication flow\",\n", " \"description\": \"Set up email/password authentication with signup, login, password reset, and email verification using Supabase Auth.\",\n", " \"priority\": \"high\",\n", " \"context\": \"Supabase Auth with Next.js middleware\",\n", " \"subtasks\": [\n", " (\"Configure Supabase Auth providers and settings\", \"high\", 2, 0.5, \"backend,auth\"),\n", " (\"Implement signup API with email verification\", \"high\", 3, 1.0, \"backend,auth\"),\n", " (\"Build login endpoint with session handling\", \"high\", 3, 1.0, \"backend,auth\"),\n", " (\"Add password reset flow\", \"medium\", 3, 1.0, \"backend,auth\"),\n", " (\"Create auth middleware for protected routes\", \"high\", 3, 1.0, \"backend,auth,middleware\"),\n", " (\"Add rate limiting on auth endpoints\", \"medium\", 2, 1.0, \"backend,security\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Create sprint management API\",\n", " \"description\": \"Build endpoints for creating sprints, adding tasks to sprints, starting/completing sprints, and calculating sprint metrics.\",\n", " \"priority\": \"high\",\n", " \"context\": \"Supabase with sprint status workflow enforcement\",\n", " \"subtasks\": [\n", " (\"Implement POST /api/sprints for creation\", \"high\", 2, 1.0, \"backend,api\"),\n", " (\"Build sprint task assignment endpoint\", \"high\", 3, 1.0, \"backend,api\"),\n", " (\"Add sprint start/complete state transitions\", \"high\", 3, 1.5, \"backend,api,workflow\"),\n", " (\"Calculate velocity and burndown metrics\", \"medium\", 5, 2.0, \"backend,analytics\"),\n", " (\"Implement sprint history and comparison\", \"low\", 3, 1.5, \"backend,api\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Set up database migration system\",\n", " \"description\": \"Establish a reliable migration workflow for the Supabase PostgreSQL database. Include seeding, rollback support, and CI integration.\",\n", " \"priority\": \"high\",\n", " \"context\": \"Supabase CLI with PostgreSQL\",\n", " \"subtasks\": [\n", " (\"Set up Supabase CLI and local dev environment\", \"high\", 2, 0.5, \"backend,devops\"),\n", " (\"Write initial schema migration with all tables\", \"high\", 5, 2.0, \"backend,database\"),\n", " (\"Create seed data script for development\", \"medium\", 3, 1.0, \"backend,database\"),\n", " (\"Document migration workflow for team\", \"low\", 1, 0.5, \"backend,docs\"),\n", " (\"Add migration check to CI pipeline\", \"medium\", 2, 1.0, \"backend,devops\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Implement real-time notifications backend\",\n", " \"description\": \"Build the server-side notification system that creates, stores, and broadcasts notifications via Supabase Realtime when events occur.\",\n", " \"priority\": \"medium\",\n", " \"context\": \"Supabase Realtime with PostgreSQL triggers\",\n", " \"subtasks\": [\n", " (\"Design notification event types and schema\", \"medium\", 2, 0.5, \"backend,design\"),\n", " (\"Create notification creation utility functions\", \"medium\", 3, 1.0, \"backend,api\"),\n", " (\"Add database triggers for task assignment events\", \"high\", 3, 1.5, \"backend,database\"),\n", " (\"Add triggers for sprint deadline events\", \"medium\", 2, 1.0, \"backend,database\"),\n", " (\"Set up Supabase Realtime channel for notifications\", \"medium\", 3, 1.0, \"backend,realtime\"),\n", " (\"Implement mark-as-read and bulk dismiss API\", \"low\", 2, 1.0, \"backend,api\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Build file upload and storage API\",\n", " \"description\": \"Create endpoints for uploading files to projects and tasks, with support for multiple file types, size limits, and version tracking.\",\n", " \"priority\": \"medium\",\n", " \"context\": \"Supabase Storage with signed URLs\",\n", " \"subtasks\": [\n", " (\"Configure Supabase Storage bucket and policies\", \"high\", 2, 0.5, \"backend,storage\"),\n", " (\"Build file upload endpoint with multipart support\", \"high\", 3, 1.5, \"backend,api\"),\n", " (\"Add file type validation and size limit checks\", \"medium\", 2, 0.5, \"backend,validation\"),\n", " (\"Implement file version tracking\", \"medium\", 3, 1.5, \"backend,storage\"),\n", " (\"Create file sharing with access control\", \"medium\", 3, 1.0, \"backend,api,security\"),\n", " (\"Add signed URL generation for downloads\", \"medium\", 2, 0.5, \"backend,api\"),\n", " ],\n", " },\n", "]\n", "\n", "DEVOPS_TASKS = [\n", " {\n", " \"title\": \"Set up CI/CD pipeline\",\n", " \"description\": \"Configure a complete CI/CD pipeline with linting, testing, building, and deployment stages. Deploy to Vercel for the Next.js frontend.\",\n", " \"priority\": \"high\",\n", " \"context\": \"GitHub Actions with Vercel deployment\",\n", " \"subtasks\": [\n", " (\"Create GitHub Actions workflow file\", \"high\", 2, 0.5, \"devops,ci\"),\n", " (\"Add lint and type-check stage\", \"medium\", 2, 0.5, \"devops,ci\"),\n", " (\"Configure test stage with coverage reporting\", \"medium\", 3, 1.0, \"devops,ci,testing\"),\n", " (\"Set up build stage with environment variables\", \"high\", 2, 0.5, \"devops,ci\"),\n", " (\"Configure Vercel deployment integration\", \"high\", 3, 1.0, \"devops,deployment\"),\n", " (\"Add Slack notifications for build status\", \"low\", 1, 0.5, \"devops,ci\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Containerize the AI server\",\n", " \"description\": \"Create a Docker setup for the FastAPI AI server with multi-stage builds, GPU support, and health checks.\",\n", " \"priority\": \"medium\",\n", " \"context\": \"Python FastAPI server with PyTorch models\",\n", " \"subtasks\": [\n", " (\"Write multi-stage Dockerfile for AI server\", \"high\", 3, 1.0, \"devops,docker\"),\n", " (\"Create docker-compose.yml with service config\", \"medium\", 2, 0.5, \"devops,docker\"),\n", " (\"Add GPU passthrough support for CUDA inference\", \"medium\", 3, 1.5, \"devops,docker,gpu\"),\n", " (\"Configure health check and restart policy\", \"medium\", 2, 0.5, \"devops,docker\"),\n", " (\"Set up volume mounts for model weights\", \"low\", 1, 0.5, \"devops,docker\"),\n", " (\"Add build and push to container registry\", \"medium\", 2, 1.0, \"devops,ci\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Configure monitoring and logging\",\n", " \"description\": \"Set up application monitoring, structured logging, and alerting for both the Next.js app and AI server.\",\n", " \"priority\": \"medium\",\n", " \"context\": \"Vercel Analytics + custom logging\",\n", " \"subtasks\": [\n", " (\"Set up structured JSON logging format\", \"medium\", 2, 0.5, \"devops,logging\"),\n", " (\"Configure log levels and rotation\", \"low\", 1, 0.5, \"devops,logging\"),\n", " (\"Add request/response logging middleware\", \"medium\", 2, 1.0, \"devops,logging\"),\n", " (\"Set up error tracking and alerting\", \"high\", 3, 1.0, \"devops,monitoring\"),\n", " (\"Create health check dashboard\", \"low\", 2, 1.0, \"devops,monitoring\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Set up staging environment\",\n", " \"description\": \"Create a staging deployment that mirrors production for testing before releases. Include separate database and environment configuration.\",\n", " \"priority\": \"medium\",\n", " \"context\": \"Vercel preview deployments with Supabase branching\",\n", " \"subtasks\": [\n", " (\"Create staging Supabase project\", \"high\", 2, 0.5, \"devops,infrastructure\"),\n", " (\"Configure staging environment variables\", \"medium\", 2, 0.5, \"devops,config\"),\n", " (\"Set up Vercel preview deployment for staging branch\", \"medium\", 2, 1.0, \"devops,deployment\"),\n", " (\"Create database seed script for staging data\", \"medium\", 3, 1.0, \"devops,database\"),\n", " (\"Document staging workflow for team\", \"low\", 1, 0.5, \"devops,docs\"),\n", " ],\n", " },\n", "]\n", "\n", "TESTING_TASKS = [\n", " {\n", " \"title\": \"Set up testing framework\",\n", " \"description\": \"Configure Jest and React Testing Library for the Next.js app. Set up test utilities, mocks, and coverage thresholds.\",\n", " \"priority\": \"high\",\n", " \"context\": \"Next.js with Jest and React Testing Library\",\n", " \"subtasks\": [\n", " (\"Install and configure Jest for Next.js\", \"high\", 2, 0.5, \"testing,setup\"),\n", " (\"Set up React Testing Library with custom render\", \"high\", 2, 0.5, \"testing,setup\"),\n", " (\"Create mock utilities for Supabase client\", \"medium\", 3, 1.0, \"testing,mocks\"),\n", " (\"Configure coverage thresholds and reporters\", \"medium\", 2, 0.5, \"testing,setup\"),\n", " (\"Write example tests as templates\", \"low\", 2, 1.0, \"testing,docs\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Write integration tests for task API\",\n", " \"description\": \"Create integration tests for all task CRUD endpoints. Test auth, validation, error cases, and database state.\",\n", " \"priority\": \"high\",\n", " \"context\": \"API routes with Supabase test database\",\n", " \"subtasks\": [\n", " (\"Set up test database and fixtures\", \"high\", 3, 1.0, \"testing,setup\"),\n", " (\"Write tests for task creation endpoint\", \"high\", 3, 1.0, \"testing,api\"),\n", " (\"Write tests for task listing with filters\", \"medium\", 3, 1.0, \"testing,api\"),\n", " (\"Write tests for task update and delete\", \"medium\", 3, 1.0, \"testing,api\"),\n", " (\"Test authorization and error handling\", \"high\", 3, 1.0, \"testing,api,security\"),\n", " (\"Add cleanup and teardown logic\", \"medium\", 1, 0.5, \"testing,setup\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Write E2E tests for critical user flows\",\n", " \"description\": \"Create end-to-end tests using Playwright for login, task creation, sprint management, and team collaboration flows.\",\n", " \"priority\": \"medium\",\n", " \"context\": \"Playwright with Next.js dev server\",\n", " \"subtasks\": [\n", " (\"Install and configure Playwright\", \"medium\", 2, 0.5, \"testing,e2e\"),\n", " (\"Write login and signup flow tests\", \"high\", 3, 1.0, \"testing,e2e,auth\"),\n", " (\"Write task creation and editing flow tests\", \"high\", 3, 1.5, \"testing,e2e\"),\n", " (\"Write sprint management flow tests\", \"medium\", 3, 1.5, \"testing,e2e\"),\n", " (\"Write team invite and collaboration tests\", \"medium\", 3, 1.5, \"testing,e2e\"),\n", " (\"Set up CI integration for E2E tests\", \"medium\", 2, 1.0, \"testing,e2e,ci\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Add unit tests for utility functions\",\n", " \"description\": \"Write comprehensive unit tests for all shared utility functions, date helpers, validation schemas, and data transformation functions.\",\n", " \"priority\": \"low\",\n", " \"context\": \"Jest with TypeScript\",\n", " \"subtasks\": [\n", " (\"Test date formatting and timezone utilities\", \"low\", 2, 0.5, \"testing,unit\"),\n", " (\"Test validation schema helpers\", \"medium\", 2, 0.5, \"testing,unit\"),\n", " (\"Test data transformation functions\", \"medium\", 2, 0.5, \"testing,unit\"),\n", " (\"Test permission checking utilities\", \"medium\", 2, 0.5, \"testing,unit\"),\n", " ],\n", " },\n", "]\n", "\n", "DESIGN_TASKS = [\n", " {\n", " \"title\": \"Design project management UI kit\",\n", " \"description\": \"Create a comprehensive UI kit with reusable components for the project management interface including task cards, sprint boards, and member avatars.\",\n", " \"priority\": \"medium\",\n", " \"context\": \"Figma design system with Tailwind-compatible tokens\",\n", " \"subtasks\": [\n", " (\"Define color palette and typography scale\", \"high\", 2, 0.5, \"design,system\"),\n", " (\"Design task card variants (compact, detailed, kanban)\", \"high\", 3, 1.5, \"design,ui\"),\n", " (\"Create sprint board layout templates\", \"medium\", 3, 1.5, \"design,ui\"),\n", " (\"Design member avatar and badge components\", \"low\", 2, 0.5, \"design,ui\"),\n", " (\"Build icon set for status and priority indicators\", \"medium\", 2, 1.0, \"design,ui\"),\n", " (\"Document component specs for developers\", \"low\", 2, 1.0, \"design,docs\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Create wireframes for AI features\",\n", " \"description\": \"Design wireframes for AI-powered features: task decomposition panel, smart assignment suggestions, and sprint risk dashboard.\",\n", " \"priority\": \"high\",\n", " \"context\": \"AI features integrated into existing PM interface\",\n", " \"subtasks\": [\n", " (\"Wireframe task decomposition suggestion panel\", \"high\", 3, 1.0, \"design,ai,wireframe\"),\n", " (\"Design assignment suggestion dropdown UI\", \"high\", 3, 1.0, \"design,ai,wireframe\"),\n", " (\"Create sprint risk dashboard wireframe\", \"high\", 5, 2.0, \"design,ai,wireframe\"),\n", " (\"Design confidence score visualizations\", \"medium\", 2, 1.0, \"design,ai\"),\n", " (\"Create user flow diagrams for AI interactions\", \"medium\", 2, 1.0, \"design,ux\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Design responsive mobile layout\",\n", " \"description\": \"Adapt the project management interface for mobile devices with touch-friendly interactions and simplified navigation.\",\n", " \"priority\": \"low\",\n", " \"context\": \"Mobile-first responsive design\",\n", " \"subtasks\": [\n", " (\"Design mobile navigation pattern\", \"medium\", 3, 1.0, \"design,mobile\"),\n", " (\"Adapt task list view for small screens\", \"medium\", 3, 1.0, \"design,mobile\"),\n", " (\"Design mobile-friendly task creation form\", \"medium\", 2, 1.0, \"design,mobile\"),\n", " (\"Create touch-friendly drag-and-drop alternative\", \"high\", 3, 1.5, \"design,mobile,ux\"),\n", " ],\n", " },\n", "]\n", "\n", "DOCUMENTATION_TASKS = [\n", " {\n", " \"title\": \"Write API documentation\",\n", " \"description\": \"Create comprehensive API documentation for all endpoints including request/response examples, error codes, and authentication guide.\",\n", " \"priority\": \"medium\",\n", " \"context\": \"REST API with OpenAPI/Swagger\",\n", " \"subtasks\": [\n", " (\"Document authentication and API key setup\", \"high\", 2, 0.5, \"docs,api\"),\n", " (\"Write endpoint reference for task APIs\", \"medium\", 3, 1.5, \"docs,api\"),\n", " (\"Write endpoint reference for sprint APIs\", \"medium\", 3, 1.5, \"docs,api\"),\n", " (\"Add request/response examples for each endpoint\", \"medium\", 3, 1.0, \"docs,api\"),\n", " (\"Document error codes and troubleshooting\", \"low\", 2, 1.0, \"docs,api\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Create developer setup guide\",\n", " \"description\": \"Write a getting-started guide for new developers joining the project. Cover environment setup, dependencies, database configuration, and running locally.\",\n", " \"priority\": \"high\",\n", " \"context\": \"Next.js + Supabase + Python AI server\",\n", " \"subtasks\": [\n", " (\"Document prerequisite software and versions\", \"high\", 1, 0.5, \"docs,setup\"),\n", " (\"Write Next.js app setup instructions\", \"high\", 2, 0.5, \"docs,setup\"),\n", " (\"Write Supabase local setup and migration guide\", \"high\", 2, 1.0, \"docs,setup\"),\n", " (\"Document AI server Python setup\", \"medium\", 2, 1.0, \"docs,setup\"),\n", " (\"Add troubleshooting FAQ section\", \"low\", 2, 1.0, \"docs,setup\"),\n", " ],\n", " },\n", " {\n", " \"title\": \"Write architecture decision records\",\n", " \"description\": \"Document key architectural decisions including technology choices, data model design, AI model selection, and deployment strategy.\",\n", " \"priority\": \"low\",\n", " \"context\": \"ADR format for FYP documentation\",\n", " \"subtasks\": [\n", " (\"Document technology stack selection rationale\", \"medium\", 2, 1.0, \"docs,architecture\"),\n", " (\"Write data model and schema design ADR\", \"medium\", 3, 1.5, \"docs,architecture\"),\n", " (\"Document AI model architecture decisions\", \"medium\", 3, 1.5, \"docs,architecture\"),\n", " (\"Write deployment and infrastructure ADR\", \"low\", 2, 1.0, \"docs,architecture\"),\n", " ],\n", " },\n", "]\n", "\n", "ALL_CATEGORIES = {\n", " \"frontend\": FRONTEND_TASKS,\n", " \"backend\": BACKEND_TASKS,\n", " \"devops\": DEVOPS_TASKS,\n", " \"testing\": TESTING_TASKS,\n", " \"design\": DESIGN_TASKS,\n", " \"documentation\": DOCUMENTATION_TASKS,\n", "}\n", "\n", "# --- Build training examples ---\n", "\n", "def format_input(task: dict) -> str:\n", " \"\"\"Build the model input prompt from a task dict.\"\"\"\n", " return (\n", " f\"Decompose this software task into subtasks:\\n\"\n", " f\"Task: {task['title']}\\n\"\n", " f\"Description: {task['description']}\\n\"\n", " f\"Priority: {task['priority']}\\n\"\n", " f\"Context: {task['context']}\"\n", " )\n", "\n", "def format_output(subtasks: list[tuple]) -> str:\n", " \"\"\"Build the structured output from a list of subtask tuples.\"\"\"\n", " lines = []\n", " for i, (title, priority, points, days, tags) in enumerate(subtasks, 1):\n", " lines.append(\n", " f\"SUBTASK_{i}: {title} | PRIORITY: {priority} | \"\n", " f\"POINTS: {points} | DAYS: {days} | TAGS: {tags}\"\n", " )\n", " return \"\\n\".join(lines)\n", "\n", "\n", "# Variation generators for data augmentation\n", "PRIORITY_MAP = [\"low\", \"medium\", \"high\", \"urgent\"]\n", "\n", "TITLE_PREFIXES = [\n", " \"Implement\", \"Build\", \"Create\", \"Set up\", \"Configure\",\n", " \"Design\", \"Write\", \"Add\", \"Refactor\", \"Fix\",\n", " \"Integrate\", \"Optimize\", \"Migrate\", \"Update\", \"Deploy\",\n", "]\n", "\n", "DESCRIPTION_VARIATIONS = [\n", " \"This involves {action} with proper error handling and validation.\",\n", " \"We need to {action}. Should follow best practices and be well-tested.\",\n", " \"{action}. Include documentation and code review.\",\n", " \"The goal is to {action} while maintaining backward compatibility.\",\n", " \"{action}. This is part of the core feature set.\",\n", "]\n", "\n", "CONTEXT_TEMPLATES = [\n", " \"React/Next.js project with TypeScript and Tailwind CSS\",\n", " \"Supabase backend with PostgreSQL and Row Level Security\",\n", " \"Python FastAPI server with ML model inference\",\n", " \"Full-stack project with Next.js frontend and Supabase backend\",\n", " \"Agile team with 2-week sprints and CI/CD pipeline\",\n", "]\n", "\n", "\n", "def generate_augmented_examples(base_tasks: list[dict], category: str, count: int) -> list[dict]:\n", " \"\"\"Generate augmented variations from base task templates.\"\"\"\n", " examples = []\n", "\n", " # First, add all base examples as-is\n", " for task in base_tasks:\n", " examples.append({\n", " \"input_text\": format_input(task),\n", " \"target_text\": format_output(task[\"subtasks\"]),\n", " })\n", "\n", " # Then generate variations\n", " while len(examples) < count:\n", " task = random.choice(base_tasks)\n", "\n", " # Vary the priority\n", " new_priority = random.choice(PRIORITY_MAP)\n", "\n", " # Slight variation in title\n", " prefix = random.choice(TITLE_PREFIXES)\n", " base_title = task[\"title\"]\n", " # Sometimes swap the prefix\n", " for p in TITLE_PREFIXES:\n", " if base_title.startswith(p):\n", " base_title = base_title[len(p):].strip()\n", " break\n", " new_title = f\"{prefix} {base_title}\"\n", "\n", " # Vary context\n", " new_context = random.choice(CONTEXT_TEMPLATES)\n", "\n", " # Vary subtask points slightly\n", " new_subtasks = []\n", " for title, prio, points, days, tags in task[\"subtasks\"]:\n", " # Small random perturbation\n", " point_options = [max(1, points - 1), points, min(13, points + 1)]\n", " new_points = random.choice([p for p in point_options if p in {1,2,3,5,8,13}] or [points])\n", " day_delta = random.choice([-0.5, 0, 0, 0.5])\n", " new_days = max(0.5, days + day_delta)\n", " new_prio = prio if random.random() > 0.3 else new_priority\n", " new_subtasks.append((title, new_prio, new_points, new_days, tags))\n", "\n", " varied = {\n", " \"title\": new_title,\n", " \"description\": task[\"description\"],\n", " \"priority\": new_priority,\n", " \"context\": new_context,\n", " \"subtasks\": new_subtasks,\n", " }\n", "\n", " examples.append({\n", " \"input_text\": format_input(varied),\n", " \"target_text\": format_output(varied[\"subtasks\"]),\n", " })\n", "\n", " return examples[:count]\n", "\n", "\n", "# Generate examples per category\n", "TARGET_PER_CATEGORY = 350 # 350 * 6 = 2100, plus structural = ~2500-2600\n", "all_examples = []\n", "\n", "for cat_name, cat_tasks in ALL_CATEGORIES.items():\n", " cat_examples = generate_augmented_examples(cat_tasks, cat_name, TARGET_PER_CATEGORY)\n", " all_examples.extend(cat_examples)\n", " print(f\" {cat_name}: {len(cat_examples)} examples\")\n", "\n", "# Add structural pattern examples\n", "all_examples.extend(structural_examples)\n", "\n", "# Shuffle\n", "random.shuffle(all_examples)\n", "\n", "print(f\"\\nTotal training examples: {len(all_examples)}\")\n", "\n", "# Split into train / validation / test (80/10/10)\n", "n = len(all_examples)\n", "train_end = int(0.8 * n)\n", "val_end = int(0.9 * n)\n", "\n", "train_data = all_examples[:train_end]\n", "val_data = all_examples[train_end:val_end]\n", "test_data = all_examples[val_end:]\n", "\n", "print(f\"Train: {len(train_data)}, Validation: {len(val_data)}, Test: {len(test_data)}\")\n", "\n", "# Convert to HuggingFace Dataset\n", "dataset = DatasetDict({\n", " \"train\": Dataset.from_list(train_data),\n", " \"validation\": Dataset.from_list(val_data),\n", " \"test\": Dataset.from_list(test_data),\n", "})\n", "print(f\"\\nDataset:\\n{dataset}\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Tokenization\n", "\n", "We load the FLAN-T5-small tokenizer and tokenize all examples.\n", "- **Max input length:** 512 tokens (task descriptions can be verbose)\n", "- **Max output length:** 256 tokens (subtask lists are structured but compact)\n", "- **Padding:** to longest in batch (saves memory vs fixed padding)" ] }, { "cell_type": "code", "metadata": {}, "source": [ "# ============================================================================\n", "# SECTION 4: Tokenization\n", "# ============================================================================\n", "\n", "print(\"\\n\" + \"=\"*60)\n", "print(\"SECTION 4: Tokenizing dataset\")\n", "print(\"=\"*60)\n", "\n", "MODEL_NAME = \"google/flan-t5-small\"\n", "MAX_INPUT_LENGTH = 512\n", "MAX_TARGET_LENGTH = 256\n", "\n", "tokenizer = T5Tokenizer.from_pretrained(MODEL_NAME)\n", "print(f\"Loaded tokenizer: {MODEL_NAME}\")\n", "print(f\"Vocab size: {tokenizer.vocab_size}\")\n", "\n", "\n", "def tokenize_function(examples):\n", " \"\"\"Tokenize input-output pairs for seq2seq training.\"\"\"\n", " model_inputs = tokenizer(\n", " examples[\"input_text\"],\n", " max_length=MAX_INPUT_LENGTH,\n", " truncation=True,\n", " padding=\"max_length\",\n", " )\n", "\n", " labels = tokenizer(\n", " examples[\"target_text\"],\n", " max_length=MAX_TARGET_LENGTH,\n", " truncation=True,\n", " padding=\"max_length\",\n", " )\n", "\n", " # Replace padding token ids in labels with -100 so they're ignored in loss\n", " labels[\"input_ids\"] = [\n", " [(l if l != tokenizer.pad_token_id else -100) for l in label]\n", " for label in labels[\"input_ids\"]\n", " ]\n", "\n", " model_inputs[\"labels\"] = labels[\"input_ids\"]\n", " return model_inputs\n", "\n", "\n", "tokenized_dataset = dataset.map(\n", " tokenize_function,\n", " batched=True,\n", " remove_columns=[\"input_text\", \"target_text\"],\n", " desc=\"Tokenizing\",\n", ")\n", "\n", "print(f\"\\nTokenized dataset:\\n{tokenized_dataset}\")\n", "\n", "# Sanity check: decode a sample\n", "sample_idx = 0\n", "sample_input = tokenizer.decode(\n", " tokenized_dataset[\"train\"][sample_idx][\"input_ids\"],\n", " skip_special_tokens=True,\n", ")\n", "sample_label_ids = [\n", " t if t != -100 else tokenizer.pad_token_id\n", " for t in tokenized_dataset[\"train\"][sample_idx][\"labels\"]\n", "]\n", "sample_target = tokenizer.decode(sample_label_ids, skip_special_tokens=True)\n", "print(f\"\\n--- Sample {sample_idx} ---\")\n", "print(f\"INPUT:\\n{sample_input[:300]}...\")\n", "print(f\"\\nTARGET:\\n{sample_target[:300]}...\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Fine-tuning\n", "\n", "We fine-tune FLAN-T5-small with these hyperparameters:\n", "- **Epochs:** 5\n", "- **Batch size:** 8 (fits in Colab T4 free GPU with 15 GB VRAM)\n", "- **Learning rate:** 3e-4 with linear warmup over 100 steps\n", "- **Evaluation:** every 200 steps\n", "- **Best checkpoint:** saved by ROUGE-L score\n", "- **FP16:** enabled for T4 GPU memory efficiency\n", "\n", "Expected training time on T4: ~45-90 minutes." ] }, { "cell_type": "code", "metadata": {}, "source": [ "# ============================================================================\n", "# SECTION 5: Fine-tuning\n", "# ============================================================================\n", "\n", "print(\"\\n\" + \"=\"*60)\n", "print(\"SECTION 5: Fine-tuning FLAN-T5-small\")\n", "print(\"=\"*60)\n", "\n", "# Load model\n", "model = T5ForConditionalGeneration.from_pretrained(MODEL_NAME)\n", "print(f\"Model parameters: {model.num_parameters() / 1e6:.1f}M\")\n", "\n", "# ROUGE metric for evaluation\n", "rouge_metric = evaluate.load(\"rouge\")\n", "\n", "\n", "def compute_metrics(eval_preds):\n", " \"\"\"Compute ROUGE scores for evaluation.\"\"\"\n", " preds, labels = eval_preds\n", "\n", " # Decode predictions\n", " # Clip predictions to valid token range to prevent OverflowError\n", " preds = np.clip(preds, 0, tokenizer.vocab_size - 1)\n", " \n", " decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)\n", "\n", " # Replace -100 in labels with pad token for decoding\n", " labels = np.where(labels != -100, labels, tokenizer.pad_token_id)\n", " decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)\n", "\n", " # Strip whitespace\n", " decoded_preds = [pred.strip() for pred in decoded_preds]\n", " decoded_labels = [label.strip() for label in decoded_labels]\n", "\n", " result = rouge_metric.compute(\n", " predictions=decoded_preds,\n", " references=decoded_labels,\n", " use_stemmer=True,\n", " )\n", "\n", " return {\n", " \"rouge1\": round(result[\"rouge1\"], 4),\n", " \"rouge2\": round(result[\"rouge2\"], 4),\n", " \"rougeL\": round(result[\"rougeL\"], 4),\n", " }\n", "\n", "\n", "# Output directory\n", "OUTPUT_DIR = \"/content/flan-t5-pm-decomposition\" if os.path.exists(\"/content\") else \"./flan-t5-pm-decomposition\"\n", "LOGGING_DIR = os.path.join(OUTPUT_DIR, \"logs\")\n", "\n", "training_args = Seq2SeqTrainingArguments(\n", " output_dir=OUTPUT_DIR,\n", " num_train_epochs=5,\n", " per_device_train_batch_size=8,\n", " per_device_eval_batch_size=8,\n", " learning_rate=3e-4,\n", " warmup_steps=100,\n", " weight_decay=0.01,\n", " lr_scheduler_type=\"linear\",\n", " # Evaluation\n", " eval_strategy=\"steps\",\n", " eval_steps=200,\n", " save_strategy=\"steps\",\n", " save_steps=200,\n", " save_total_limit=3,\n", " load_best_model_at_end=True,\n", " metric_for_best_model=\"rougeL\",\n", " greater_is_better=True,\n", " # Generation config for evaluation\n", " predict_with_generate=True,\n", " generation_max_length=MAX_TARGET_LENGTH,\n", " # Performance\n", " fp16=torch.cuda.is_available(),\n", " dataloader_num_workers=2,\n", " # Logging\n", " logging_dir=LOGGING_DIR,\n", " logging_steps=50,\n", " report_to=\"none\", # Set to \"tensorboard\" if you want TB logging\n", " # Misc\n", " seed=SEED,\n", " push_to_hub=False,\n", ")\n", "\n", "data_collator = DataCollatorForSeq2Seq(\n", " tokenizer=tokenizer,\n", " model=model,\n", " padding=True,\n", " label_pad_token_id=-100,\n", ")\n", "\n", "trainer = Seq2SeqTrainer(\n", " model=model,\n", " args=training_args,\n", " train_dataset=tokenized_dataset[\"train\"],\n", " eval_dataset=tokenized_dataset[\"validation\"],\n", " processing_class=tokenizer,\n", " data_collator=data_collator,\n", " compute_metrics=compute_metrics,\n", " callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],\n", ")\n", "\n", "print(f\"\\nTraining configuration:\")\n", "print(f\" Epochs: {training_args.num_train_epochs}\")\n", "print(f\" Batch size: {training_args.per_device_train_batch_size}\")\n", "print(f\" Learning rate: {training_args.learning_rate}\")\n", "print(f\" Warmup steps: {training_args.warmup_steps}\")\n", "print(f\" Eval every: {training_args.eval_steps} steps\")\n", "print(f\" FP16: {training_args.fp16}\")\n", "print(f\" Output: {OUTPUT_DIR}\")\n", "\n", "print(f\"\\nStarting training...\")\n", "train_result = trainer.train()\n", "\n", "print(f\"\\n--- Training Complete ---\")\n", "print(f\" Total steps: {train_result.metrics.get('train_steps', 'N/A')}\")\n", "print(f\" Training loss: {train_result.metrics.get('train_loss', 'N/A')}\")\n", "print(f\" Training time: {train_result.metrics.get('train_runtime', 0):.0f}s\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Evaluation\n", "\n", "We evaluate the fine-tuned model on the held-out test set using:\n", "- **ROUGE-1:** Unigram overlap (individual word matching)\n", "- **ROUGE-2:** Bigram overlap (two-word phrase matching)\n", "- **ROUGE-L:** Longest common subsequence (structural similarity)\n", "\n", "We also manually inspect 10 predictions to qualitatively assess output quality.\n", "Target: ROUGE-L > 0.35 (reasonable for this task and dataset size)." ] }, { "cell_type": "code", "metadata": {}, "source": [ "# ============================================================================\n", "# SECTION 6: Evaluation\n", "# ============================================================================\n", "\n", "print(\"\\n\" + \"=\"*60)\n", "print(\"SECTION 6: Evaluation\")\n", "print(\"=\"*60)\n", "\n", "# Evaluate on test set\n", "test_results = trainer.evaluate(tokenized_dataset[\"test\"])\n", "print(f\"\\n--- Test Set Results ---\")\n", "print(f\" ROUGE-1: {test_results.get('eval_rouge1', 'N/A')}\")\n", "print(f\" ROUGE-2: {test_results.get('eval_rouge2', 'N/A')}\")\n", "print(f\" ROUGE-L: {test_results.get('eval_rougeL', 'N/A')}\")\n", "print(f\" Eval Loss: {test_results.get('eval_loss', 'N/A'):.4f}\")\n", "\n", "rouge_l = test_results.get(\"eval_rougeL\", 0)\n", "if rouge_l >= 0.35:\n", " print(f\"\\n TARGET MET: ROUGE-L {rouge_l:.4f} >= 0.35\")\n", "else:\n", " print(f\"\\n TARGET NOT MET: ROUGE-L {rouge_l:.4f} < 0.35\")\n", " print(\" Consider: more training data, more epochs, or larger model\")\n", "\n", "# Manual inspection: generate predictions for 10 test examples\n", "print(f\"\\n--- Manual Inspection (10 test examples) ---\")\n", "\n", "model.eval()\n", "for i in range(min(10, len(test_data))):\n", " input_text = test_data[i][\"input_text\"]\n", " expected = test_data[i][\"target_text\"]\n", "\n", " inputs = tokenizer(\n", " input_text,\n", " return_tensors=\"pt\",\n", " max_length=MAX_INPUT_LENGTH,\n", " truncation=True,\n", " ).to(model.device)\n", "\n", " with torch.no_grad():\n", " outputs = model.generate(\n", " **inputs,\n", " max_new_tokens=MAX_TARGET_LENGTH,\n", " num_beams=4,\n", " early_stopping=True,\n", " do_sample=False,\n", " )\n", "\n", " predicted = tokenizer.decode(outputs[0], skip_special_tokens=True)\n", "\n", " print(f\"\\n{'='*50}\")\n", " print(f\"Example {i+1}\")\n", " print(f\"{'='*50}\")\n", " # Print just the task title from input\n", " title_line = [l for l in input_text.split(\"\\n\") if l.startswith(\"Task:\")]\n", " print(f\"TASK: {title_line[0] if title_line else input_text[:80]}\")\n", " print(f\"\\nEXPECTED:\\n{expected[:200]}\")\n", " print(f\"\\nPREDICTED:\\n{predicted[:200]}\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. Save & Export\n", "\n", "We save the fine-tuned model and tokenizer, then create a zip archive\n", "for download. The saved model can be placed directly into the AI server's\n", "`model_weights/decomposition/` directory.\n", "\n", "Model size is approximately 300 MB (FLAN-T5-small)." ] }, { "cell_type": "code", "metadata": {}, "source": [ "# ============================================================================\n", "# SECTION 7: Save & Export\n", "# ============================================================================\n", "\n", "print(\"\\n\" + \"=\"*60)\n", "print(\"SECTION 7: Save & Export\")\n", "print(\"=\"*60)\n", "\n", "SAVE_DIR = OUTPUT_DIR # reuse the output dir from training\n", "\n", "# Save model and tokenizer\n", "trainer.save_model(SAVE_DIR)\n", "tokenizer.save_pretrained(SAVE_DIR)\n", "\n", "# Save training metadata\n", "metadata = {\n", " \"model_name\": MODEL_NAME,\n", " \"model_version\": \"flan-t5-pm-v1\",\n", " \"fine_tuned_on\": \"synthetic-pm-decomposition\",\n", " \"training_examples\": len(train_data),\n", " \"validation_examples\": len(val_data),\n", " \"test_examples\": len(test_data),\n", " \"epochs\": int(training_args.num_train_epochs),\n", " \"batch_size\": training_args.per_device_train_batch_size,\n", " \"learning_rate\": training_args.learning_rate,\n", " \"test_rouge1\": test_results.get(\"eval_rouge1\"),\n", " \"test_rouge2\": test_results.get(\"eval_rouge2\"),\n", " \"test_rougeL\": test_results.get(\"eval_rougeL\"),\n", " \"max_input_length\": MAX_INPUT_LENGTH,\n", " \"max_target_length\": MAX_TARGET_LENGTH,\n", " \"output_format\": \"SUBTASK_N: title | PRIORITY: p | POINTS: n | DAYS: n | TAGS: t1,t2\",\n", "}\n", "\n", "with open(os.path.join(SAVE_DIR, \"training_metadata.json\"), \"w\") as f:\n", " json.dump(metadata, f, indent=2)\n", "print(f\"Saved training metadata to {SAVE_DIR}/training_metadata.json\")\n", "\n", "# Calculate model size\n", "total_size = 0\n", "for root, dirs, files in os.walk(SAVE_DIR):\n", " for file in files:\n", " fp = os.path.join(root, file)\n", " if not os.path.islink(fp):\n", " total_size += os.path.getsize(fp)\n", "\n", "print(f\"\\nModel saved to: {SAVE_DIR}\")\n", "print(f\"Model size: {total_size / 1e6:.1f} MB\")\n", "\n", "# List saved files\n", "print(f\"\\nSaved files:\")\n", "for f in sorted(os.listdir(SAVE_DIR)):\n", " fp = os.path.join(SAVE_DIR, f)\n", " if os.path.isfile(fp):\n", " size = os.path.getsize(fp)\n", " print(f\" {f}: {size / 1e6:.1f} MB\" if size > 1e6 else f\" {f}: {size / 1e3:.1f} KB\")\n", "\n", "# Zip for download\n", "import shutil\n", "zip_path = shutil.make_archive(\n", " base_name=SAVE_DIR,\n", " format=\"zip\",\n", " root_dir=os.path.dirname(SAVE_DIR),\n", " base_dir=os.path.basename(SAVE_DIR),\n", ")\n", "zip_size = os.path.getsize(zip_path)\n", "print(f\"\\nZip archive: {zip_path} ({zip_size / 1e6:.1f} MB)\")\n", "\n", "# Download in Colab\n", "try:\n", " from google.colab import files\n", " print(\"Downloading zip to your browser...\")\n", " files.download(zip_path)\n", "except ImportError:\n", " print(f\"Not in Colab — zip saved locally at: {zip_path}\")\n", "\n", "# Optional: push to HuggingFace Hub\n", "# Uncomment and set your token to push:\n", "# from huggingface_hub import login\n", "# login(token=\"hf_YOUR_TOKEN\")\n", "# model.push_to_hub(\"your-username/flan-t5-pm-decomposition\")\n", "# tokenizer.push_to_hub(\"your-username/flan-t5-pm-decomposition\")\n", "# print(\"Pushed to HuggingFace Hub!\")\n", "\n", "print(\"\\n\" + \"=\"*60)\n", "print(\"TRAINING COMPLETE\")\n", "print(\"=\"*60)\n", "print(f\"\\nTo use this model in the AI server:\")\n", "print(f\" 1. Unzip {os.path.basename(zip_path)}\")\n", "print(f\" 2. Copy contents to ai-server/model_weights/decomposition/\")\n", "print(f\" 3. Restart the AI server\")\n", "print(f\" 4. Check /health — decomposition should show true\")" ], "execution_count": null, "outputs": [] } ] }