File size: 10,760 Bytes
5426684 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | import React, { useEffect, useRef, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { TrainingStatus } from '../types';
import { CheckCircle, Activity, Clock } from 'lucide-react';
import { useApi } from '@/contexts/ApiContext';
import { getJobMetricsHistory } from '@/lib/jobsApi';
import {
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts';
interface MonitoringStatsProps {
jobId: string;
trainingStatus: TrainingStatus;
getProgressPercentage: () => number;
formatTime: (seconds: number) => string;
}
interface LossPoint {
step: number;
loss: number;
}
interface LrPoint {
step: number;
lr: number;
}
const HISTORY_CAP = 2000;
const MonitoringStats: React.FC<MonitoringStatsProps> = ({
jobId,
trainingStatus,
getProgressPercentage,
formatTime,
}) => {
const [lossHistory, setLossHistory] = useState<LossPoint[]>([]);
const [lrHistory, setLrHistory] = useState<LrPoint[]>([]);
const lastStepRef = useRef(0);
const { baseUrl, fetchWithHeaders } = useApi();
// Seed the curves from the persisted log on mount (and when the active job
// changes). Without this, the chart starts empty on every page reload,
// after navigating away and back, or after a lelab restart re-attaches to
// a still-running job. Live-append continues from the last seeded step.
useEffect(() => {
let cancelled = false;
getJobMetricsHistory(baseUrl, fetchWithHeaders, jobId)
.then((points) => {
if (cancelled || points.length === 0) return;
const lossSeed: LossPoint[] = points
.filter((p) => p.loss != null)
.map((p) => ({ step: p.step, loss: p.loss as number }))
.slice(-HISTORY_CAP);
const lrSeed: LrPoint[] = points
.filter((p) => p.lr != null)
.map((p) => ({ step: p.step, lr: p.lr as number }))
.slice(-HISTORY_CAP);
setLossHistory(lossSeed);
setLrHistory(lrSeed);
// Pin lastStepRef to the last seeded step so the first live tick
// (whose step is >= the seed's last step) doesn't trigger the
// step-regressed reset in the live-append effect below.
const lastSeededStep = points[points.length - 1]?.step ?? 0;
lastStepRef.current = lastSeededStep;
})
.catch(() => {
// 404 or transient — fall through; live ticks will populate from empty.
});
return () => {
cancelled = true;
};
}, [baseUrl, fetchWithHeaders, jobId]);
// Append new metric points as they arrive; reset when a new run starts
// (current_step resets back to 0).
useEffect(() => {
const step = trainingStatus.current_step;
if (step < lastStepRef.current) {
setLossHistory([]);
setLrHistory([]);
}
lastStepRef.current = step;
if (step > 0 && trainingStatus.current_loss != null) {
const loss = trainingStatus.current_loss;
setLossHistory((prev) => {
const last = prev[prev.length - 1];
if (last && last.step === step) return prev;
return [...prev, { step, loss }].slice(-HISTORY_CAP);
});
}
if (step > 0 && trainingStatus.current_lr != null) {
const lr = trainingStatus.current_lr;
setLrHistory((prev) => {
const last = prev[prev.length - 1];
if (last && last.step === step) return prev;
return [...prev, { step, lr }].slice(-HISTORY_CAP);
});
}
}, [trainingStatus.current_step, trainingStatus.current_loss, trainingStatus.current_lr]);
const progress = getProgressPercentage();
// Until tqdm fires its first progress line, total_steps is 0 — show
// "Training starting…" instead of a misleading 0/0 0% reading.
const isStarting = trainingStatus.training_active && trainingStatus.total_steps === 0;
const stepLabel = isStarting
? 'Training starting…'
: `${trainingStatus.current_step.toLocaleString()} / ${trainingStatus.total_steps.toLocaleString()}`;
const etaLabel =
trainingStatus.eta_seconds != null ? formatTime(trainingStatus.eta_seconds) : '—';
return (
<div className="space-y-6">
<Card className="bg-slate-800/50 border-slate-700 rounded-xl">
<CardContent className="p-6">
<div className="flex items-baseline justify-between mb-3">
<div className="flex items-center gap-3">
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-blue-500/20 text-blue-400">
<Activity className="w-5 h-5" />
</div>
<div>
<h3 className="text-sm text-slate-400">Progress</h3>
<div className="text-base font-semibold text-white">{stepLabel}</div>
</div>
</div>
<div className="flex items-center gap-2 text-slate-300">
<Clock className="w-4 h-4 text-purple-400" />
<span className="text-sm">
ETA <span className="font-semibold text-white">{etaLabel}</span>
</span>
</div>
</div>
<div className="relative h-8 w-full overflow-hidden rounded-md bg-slate-900 border border-slate-700">
<div
className="h-full bg-gradient-to-r from-blue-500 to-sky-400 transition-[width] duration-500"
style={{ width: `${progress}%` }}
/>
<div className="absolute inset-0 flex items-center justify-center font-semibold text-white text-sm tabular-nums drop-shadow">
{isStarting ? 'warming up…' : `${progress.toFixed(1)}%`}
</div>
</div>
</CardContent>
</Card>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card className="bg-slate-800/50 border-slate-700 rounded-xl">
<CardHeader className="pb-2">
<CardTitle className="flex items-center gap-3 text-white text-base">
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-green-500/20 text-green-400">
<CheckCircle className="w-4 h-4" />
</div>
<span>
Loss{' '}
<span className="text-slate-400 text-sm font-normal">
({trainingStatus.current_loss?.toFixed(4) ?? '—'})
</span>
</span>
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<div className="h-48">
{lossHistory.length === 0 ? (
<div className="flex h-full items-center justify-center text-slate-500 text-sm">
Waiting for first metric tick…
</div>
) : (
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={lossHistory}
margin={{ top: 8, right: 12, left: 0, bottom: 0 }}
>
<XAxis
dataKey="step"
tick={{ fill: '#94a3b8', fontSize: 11 }}
stroke="#475569"
/>
<YAxis
tick={{ fill: '#94a3b8', fontSize: 11 }}
stroke="#475569"
width={48}
/>
<Tooltip
contentStyle={{
background: '#1e293b',
border: '1px solid #475569',
borderRadius: 8,
}}
labelStyle={{ color: '#cbd5e1' }}
itemStyle={{ color: '#34d399' }}
formatter={(v: number) => v.toFixed(4)}
/>
<Line
type="monotone"
dataKey="loss"
stroke="#34d399"
strokeWidth={2}
dot={false}
isAnimationActive={false}
/>
</LineChart>
</ResponsiveContainer>
)}
</div>
</CardContent>
</Card>
<Card className="bg-slate-800/50 border-slate-700 rounded-xl">
<CardHeader className="pb-2">
<CardTitle className="flex items-center gap-3 text-white text-base">
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-orange-500/20 text-orange-400">
<Activity className="w-4 h-4" />
</div>
<span>
Learning Rate{' '}
<span className="text-slate-400 text-sm font-normal">
({trainingStatus.current_lr?.toExponential(2) ?? '—'})
</span>
</span>
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<div className="h-48">
{lrHistory.length === 0 ? (
<div className="flex h-full items-center justify-center text-slate-500 text-sm">
Waiting for first metric tick…
</div>
) : (
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={lrHistory}
margin={{ top: 8, right: 12, left: 0, bottom: 0 }}
>
<XAxis
dataKey="step"
tick={{ fill: '#94a3b8', fontSize: 11 }}
stroke="#475569"
/>
<YAxis
tick={{ fill: '#94a3b8', fontSize: 11 }}
stroke="#475569"
width={48}
tickFormatter={(v: number) => v.toExponential(0)}
/>
<Tooltip
contentStyle={{
background: '#1e293b',
border: '1px solid #475569',
borderRadius: 8,
}}
labelStyle={{ color: '#cbd5e1' }}
itemStyle={{ color: '#fb923c' }}
formatter={(v: number) => v.toExponential(2)}
/>
<Line
type="monotone"
dataKey="lr"
stroke="#fb923c"
strokeWidth={2}
dot={false}
isAnimationActive={false}
/>
</LineChart>
</ResponsiveContainer>
)}
</div>
</CardContent>
</Card>
</div>
</div>
);
};
export default MonitoringStats;
|