Spaces:
Running
Running
File size: 23,270 Bytes
98847a8 ed37070 98847a8 f76d503 98847a8 f76d503 98847a8 ed37070 98847a8 f76d503 98847a8 f76d503 98847a8 ed37070 98847a8 f76d503 98847a8 ed37070 f76d503 98847a8 f76d503 98847a8 ed37070 f76d503 98847a8 ed37070 98847a8 ed37070 98847a8 ed37070 98847a8 f76d503 98847a8 f76d503 98847a8 f76d503 98847a8 |
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 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 |
import React, { useEffect, useState } from 'react'
import API from '../API'
import LeaderboardFilter from './LeaderboardFilter'
interface LeaderboardTableProps {
file: string
}
interface Row {
metric: string
[key: string]: string | number
}
interface Groups {
[group: string]: { [subgroup: string]: string[] }
}
interface GroupStats {
average: { [key: string]: number }
stdDev: { [key: string]: number }
}
const LeaderboardTable: React.FC<LeaderboardTableProps> = ({ file }) => {
const [tableRows, setTableRows] = useState<Row[]>([])
const [tableHeader, setTableHeader] = useState<string[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [groups, setGroups] = useState<Groups>({})
const [openGroups, setOpenGroups] = useState<{ [key: string]: boolean }>({})
const [openSubGroups, setOpenSubGroups] = useState<{ [key: string]: { [key: string]: boolean } }>(
{}
)
const [selectedMetrics, setSelectedMetrics] = useState<Set<string>>(new Set())
const [defaultSelectedMetrics, setDefaultSelectedMetrics] = useState<string[]>([])
// To store the unique metrics from the Overall group
const [overallMetrics, setOverallMetrics] = useState<string[]>([])
useEffect(() => {
API.fetchStaticFile(`data/${file}_benchmark.csv`)
.then((response) => {
const data = JSON.parse(response)
const rows: Row[] = data['rows']
const groups = data['groups'] as { [key: string]: string[] }
// Extract unique metrics from the Overall group (after the underscore)
const overallGroup = groups['Overall'] || []
const uniqueMetrics = new Set<string>()
overallGroup.forEach((metric) => {
if (metric.includes('_')) {
// Extract the part after the first underscore
const metricName = metric.split('_').slice(1).join('_')
uniqueMetrics.add(metricName)
}
})
setOverallMetrics(Array.from(uniqueMetrics).sort())
// Each value of groups is a list of metrics, group them by the first part of the metric before the first _
const groupsData = Object.entries(groups)
.sort(([groupA], [groupB]) => {
// Make sure "overall" comes first
if (groupA === 'Overall') return -1
if (groupB === 'Overall') return 1
// Otherwise sort alphabetically
return groupA.localeCompare(groupB)
})
.reduce(
(acc, [group, metrics]) => {
// Sort metrics to ensure consistent subgroup order
const sortedMetrics = [...metrics].sort()
// Create and sort subgroups
acc[group] = sortedMetrics.reduce<{ [key: string]: string[] }>((subAcc, metric) => {
const [mainGroup, subGroup] = metric.split('_')
if (!subAcc[mainGroup]) {
subAcc[mainGroup] = []
}
subAcc[mainGroup].push(metric)
return subAcc
}, {})
// Convert to sorted entries and back to object
acc[group] = Object.fromEntries(
Object.entries(acc[group]).sort(([subGroupA], [subGroupB]) =>
subGroupA.localeCompare(subGroupB)
)
)
return acc
},
{} as { [key: string]: { [key: string]: string[] } }
)
const allKeys: string[] = Array.from(new Set(rows.flatMap((row) => Object.keys(row))))
// Remove 'metric' from headers if it exists
const headers = allKeys.filter((key) => key !== 'metric')
// Initialize open states for groups and subgroups
const initialOpenGroups: { [key: string]: boolean } = {}
const initialOpenSubGroups: { [key: string]: { [key: string]: boolean } } = {}
Object.keys(groupsData).forEach((group) => {
initialOpenGroups[group] = false
initialOpenSubGroups[group] = {}
Object.keys(groupsData[group]).forEach((subGroup) => {
initialOpenSubGroups[group][subGroup] = false
})
})
setSelectedMetrics(new Set(data['default_selected_metrics']))
setDefaultSelectedMetrics(data['default_selected_metrics'])
setTableHeader(headers)
setTableRows(rows)
setGroups(groupsData)
setOpenGroups(initialOpenGroups)
setOpenSubGroups(initialOpenSubGroups)
setLoading(false)
})
.catch((err) => {
setError('Failed to fetch JSON: ' + err.message)
setLoading(false)
})
}, [file])
const handleSelectDefaults = () => {
setSelectedMetrics(new Set(defaultSelectedMetrics))
}
const toggleGroup = (group: string) => {
setOpenGroups((prev) => ({ ...prev, [group]: !prev[group] }))
}
const toggleSubGroup = (group: string, subGroup: string) => {
setOpenSubGroups((prev) => ({
...prev,
[group]: {
...(prev[group] || {}),
[subGroup]: !prev[group]?.[subGroup],
},
}))
}
// Find all metrics matching a particular extracted metric name (like "log10_p_value")
const findAllMetricsForName = (metricName: string): string[] => {
return tableRows
.filter((row) => {
const metric = row.metric as string
if (metric.includes('_')) {
const extractedName = metric.split('_').slice(1).join('_')
return extractedName.endsWith(metricName)
}
return false
})
.map((row) => row.metric as string)
}
// Calculate average and standard deviation for a set of metrics for a specific column
const calculateStats = (
metricNames: string[],
columnKey: string
): { avg: number; stdDev: number } => {
const values = metricNames
.map((metricName) => {
const row = tableRows.find((row) => row.metric === metricName)
return row ? Number(row[columnKey]) : NaN
})
.filter((value) => !isNaN(value))
if (values.length === 0) return { avg: NaN, stdDev: NaN }
const avg = values.reduce((sum, val) => sum + val, 0) / values.length
const squareDiffs = values.map((value) => {
const diff = value - avg
return diff * diff
})
const variance = squareDiffs.reduce((sum, sqrDiff) => sum + sqrDiff, 0) / values.length
const stdDev = Math.sqrt(variance)
return { avg, stdDev }
}
// Filter metrics by group and/or subgroup
const filterMetricsByGroupAndSubgroup = (
metricNames: string[],
group: string | null = null,
subgroup: string | null = null
): string[] => {
// If no group specified, return all metrics
if (!group) return metricNames
// Get all metrics for the specified group
const groupMetrics = Object.values(groups[group] || {}).flat()
// If subgroup is specified, further filter to that subgroup
if (subgroup && groups[group]?.[subgroup]) {
return metricNames.filter(
(metric) => groups[group][subgroup].includes(metric) && selectedMetrics.has(metric)
)
}
// Otherwise return all metrics in the group
return metricNames.filter(
(metric) => groupMetrics.includes(metric) && selectedMetrics.has(metric)
)
}
return (
<div className="rounded shadow overflow-auto">
<h3 className="font-bold mb-2">{file}</h3>
{loading && <div>Loading...</div>}
{error && <div className="text-red-500">{error}</div>}
{!loading && !error && (
<div className="overflow-x-auto">
<LeaderboardFilter
groups={groups}
selectedMetrics={selectedMetrics}
setSelectedMetrics={setSelectedMetrics}
defaultSelectedMetrics={defaultSelectedMetrics}
/>
<table className="table w-full">
<thead>
<tr>
<th>Group / Subgroup</th>
{overallMetrics.map((metric) => (
<th key={metric} colSpan={tableHeader.length} className="text-center border-x">
{metric}
</th>
))}
</tr>
<tr>
<th></th>
{overallMetrics.map((metric) => (
<React.Fragment key={`header-models-${metric}`}>
{tableHeader.map((model) => (
<th key={`${metric}-${model}`} className="text-center text-xs">
{model}
</th>
))}
</React.Fragment>
))}
</tr>
</thead>
<tbody>
{/* First render each group */}
{Object.entries(groups).map(([group, subGroups]) => {
// Get all metrics for this group
const allGroupMetrics = Object.values(subGroups).flat()
// Filter to only include selected metrics
const visibleGroupMetrics = filterMetricsByGroupAndSubgroup(allGroupMetrics, group)
// Skip this group if no metrics are selected
if (visibleGroupMetrics.length === 0) return null
return (
<React.Fragment key={group}>
{/* Group row with average stats for the entire group */}
<tr
className="bg-base-200 cursor-pointer hover:bg-base-300"
onClick={() => toggleGroup(group)}
>
<td className="font-medium">
{openGroups[group] ? '▼ ' : '▶ '}
{group}
</td>
{/* For each metric column */}
{overallMetrics.map((metric) => (
// Render sub-columns for each model
<React.Fragment key={`${group}-${metric}`}>
{tableHeader.map((col) => {
// Find all metrics in this group that match the current metric name
const allMetricsWithName = findAllMetricsForName(metric)
const metricsInGroupForThisMetric = visibleGroupMetrics.filter((m) =>
allMetricsWithName.includes(m)
)
const stats = calculateStats(metricsInGroupForThisMetric, col)
return (
<td
key={`${group}-${metric}-${col}`}
className="font-medium text-center"
>
{!isNaN(stats.avg)
? `${stats.avg.toFixed(3)} ± ${stats.stdDev.toFixed(3)}`
: 'N/A'}
</td>
)
})}
</React.Fragment>
))}
</tr>
{/* Only render subgroups if group is open */}
{openGroups[group] &&
Object.entries(subGroups).map(([subGroup, metrics]) => {
// Filter to only include selected metrics in this subgroup
const visibleSubgroupMetrics = filterMetricsByGroupAndSubgroup(
metrics,
group,
subGroup
)
// Skip this subgroup if no metrics are selected
if (visibleSubgroupMetrics.length === 0) return null
return (
<React.Fragment key={`${group}-${subGroup}`}>
{/* Subgroup row with average stats for the subgroup */}
<tr
className="bg-base-100 cursor-pointer hover:bg-base-200"
onClick={() => toggleSubGroup(group, subGroup)}
>
<td className="pl-6 font-medium">
{openSubGroups[group]?.[subGroup] ? '▼ ' : '▶ '}
{subGroup}
</td>
{/* For each metric column */}
{overallMetrics.map((metric) => (
// Render sub-columns for each model
<React.Fragment key={`${group}-${subGroup}-${metric}`}>
{tableHeader.map((col) => {
// Find all metrics in this subgroup that match the current metric name
const allMetricsWithName = findAllMetricsForName(metric)
const metricsInSubgroupForThisMetric =
visibleSubgroupMetrics.filter((m) =>
allMetricsWithName.includes(m)
)
const stats = calculateStats(
metricsInSubgroupForThisMetric,
col
)
return (
<td
key={`${group}-${subGroup}-${metric}-${col}`}
className="font-medium text-center"
>
{!isNaN(stats.avg)
? `${stats.avg.toFixed(3)} ± ${stats.stdDev.toFixed(3)}`
: 'N/A'}
</td>
)
})}
</React.Fragment>
))}
</tr>
{/* Individual metric rows */}
{openSubGroups[group]?.[subGroup] &&
// Sort visibleSubgroupMetrics alphabetically by the clean metric name
[...visibleSubgroupMetrics]
.sort((a, b) => {
// Extract clean metric names (after the underscore)
console.log({ a })
// For metrics with format {category}_{strength}_{overall_metric_name},
// First sort by category, then by overall_metric_name, then by strength
// First extract the overall metric group
const getOverallMetricGroup = (metric: string) => {
for (const overall of overallMetrics) {
if (metric.endsWith(`_${overall}`) || metric === overall) {
return overall
}
}
return ''
}
const overallA = getOverallMetricGroup(a)
const overallB = getOverallMetricGroup(b)
// Extract the strength (last part before the overall metric)
const stripOverall = (metric: string, overall: string) => {
if (metric.endsWith(`_${overall}`)) {
// Remove the overall metric group and any preceding underscore
const stripped = metric.slice(
0,
metric.length - overall.length - 1
)
const parts = stripped.split('_')
return parts.length > 0 ? parts[parts.length - 1] : ''
}
return metric
}
// Extract the category (what remains after removing strength and overall_metric_name)
const getCategory = (metric: string, overall: string) => {
if (metric.endsWith(`_${overall}`)) {
const stripped = metric.slice(
0,
metric.length - overall.length - 1
)
const parts = stripped.split('_')
// Remove the last part (strength) and join the rest (category)
return parts.length > 1
? parts.slice(0, parts.length - 1).join('_')
: ''
}
return metric
}
const categoryA = getCategory(a, overallA)
const categoryB = getCategory(b, overallB)
// First sort by category
if (categoryA !== categoryB) {
return categoryA.localeCompare(categoryB)
}
// Then sort by overall metric name
if (overallA !== overallB) {
return overallA.localeCompare(overallB)
}
// Finally sort by strength
const subA = stripOverall(a, overallA)
const subB = stripOverall(b, overallB)
// Try to parse subA and subB as numbers, handling k/m/b suffixes
const parseNumber = (str: string) => {
const match = str.match(/^(\d+(?:\.\d+)?)([kKmMbB]?)$/)
if (!match) return NaN
let [_, num, suffix] = match
let value = parseFloat(num)
switch (suffix.toLowerCase()) {
case 'k':
value *= 1e3
break
case 'm':
value *= 1e6
break
case 'b':
value *= 1e9
break
}
return value
}
const numA = parseNumber(subA)
const numB = parseNumber(subB)
if (!isNaN(numA) && !isNaN(numB)) {
return numA - numB
}
// Fallback to string comparison if not both numbers
return subA.localeCompare(subB)
})
.map((metric) => {
const row = tableRows.find((r) => r.metric === metric)
if (!row) return null
// Extract the metric name (after the underscore)
const metricName = metric.includes('_')
? metric.split('_').slice(1).join('_')
: metric
return (
<tr key={metric} className="hover:bg-base-100">
<td className="pl-10">{metric}</td>
{/* For each metric column */}
{overallMetrics.map((oMetric) => {
// Only show values for the matching metric
const isMatchingMetric =
findAllMetricsForName(oMetric).includes(metric)
if (!isMatchingMetric) {
// Fill empty cells for non-matching metrics
return (
<React.Fragment key={`${metric}-${oMetric}`}>
{tableHeader.map((col) => (
<td
key={`${metric}-${oMetric}-${col}`}
className="text-center"
></td>
))}
</React.Fragment>
)
}
// Show values for the matching metric
return (
<React.Fragment key={`${metric}-${oMetric}`}>
{tableHeader.map((col) => {
const cell = row[col]
return (
<td
key={`${metric}-${oMetric}-${col}`}
className="text-center"
>
{!isNaN(Number(cell))
? Number(Number(cell).toFixed(3))
: cell}
</td>
)
})}
</React.Fragment>
)
})}
</tr>
)
})}
</React.Fragment>
)
})}
</React.Fragment>
)
})}
</tbody>
</table>
</div>
)}
</div>
)
}
export default LeaderboardTable
|