Spaces:
Build error
Build error
File size: 11,155 Bytes
8a01471 |
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 |
/**
* Layer Geometry System
*
* Generates 3D geometries for different layer types with semantic sizing.
*
* Size Encoding:
* - Width (Z) → Channels
* - Height (Y) → Spatial resolution (relative)
* - Depth (X) → Constant for flow clarity
*/
import * as THREE from 'three';
import type { HierarchyNode } from './model-hierarchy';
// ============================================================================
// Color System (Category-based, semantic)
// ============================================================================
export const LAYER_COLORS: Record<string, string> = {
// Core layers
convolution: '#4A90D9', // Blue
linear: '#9B59B6', // Purple
normalization: '#2ECC71', // Green
activation: '#F39C12', // Orange
pooling: '#1ABC9C', // Teal
// Special layers
recurrent: '#E74C3C', // Red
attention: '#E91E63', // Pink
embedding: '#00BCD4', // Cyan
regularization: '#95A5A6', // Gray
reshape: '#607D8B', // Blue Gray
// Macro categories
encoder: '#3498DB', // Bright Blue
decoder: '#9B59B6', // Purple
output: '#E74C3C', // Red
input: '#2ECC71', // Green
// Grouping
stage: '#34495E', // Dark Gray
group: '#2C3E50', // Darker Gray
// Default
other: '#7F8C8D', // Gray
};
export const LAYER_COLORS_DARK: Record<string, string> = {
convolution: '#2E5A8A',
linear: '#6E3D8A',
normalization: '#1D8A4A',
activation: '#B87410',
pooling: '#128A74',
recurrent: '#A83232',
attention: '#A31545',
embedding: '#008A9A',
regularization: '#6B7B7B',
reshape: '#455A64',
encoder: '#236B99',
decoder: '#6E3D8A',
output: '#A83232',
input: '#1D8A4A',
stage: '#2A3F50',
group: '#1E2D3A',
other: '#5A6A6D',
};
export function getLayerColor(category: string, variant: 'light' | 'dark' = 'light'): string {
const colors = variant === 'light' ? LAYER_COLORS : LAYER_COLORS_DARK;
return colors[category] || colors.other;
}
// ============================================================================
// Size Calculation
// ============================================================================
const SIZE_CONFIG = {
// Base sizes
minWidth: 0.3,
maxWidth: 2.0,
minHeight: 0.2,
maxHeight: 1.5,
baseDepth: 0.4,
// Scaling factors
channelScale: 0.003, // Logarithmic scale for channels
paramScale: 0.00001, // Scale for parameter count
// Group sizes
macroHeight: 2.0,
stageHeight: 1.5,
// Normalization
maxChannels: 2048,
maxParams: 10000000,
};
export interface LayerDimensions {
width: number; // Z-axis (channels)
height: number; // Y-axis (spatial/block)
depth: number; // X-axis (flow direction)
}
/**
* Calculate layer dimensions based on channels and parameters
*/
export function calculateLayerDimensions(node: HierarchyNode): LayerDimensions {
const channels = node.channelSize || 64;
const params = node.totalParams || 0;
// Logarithmic scaling for width (channels)
const normalizedChannels = Math.log2(Math.max(channels, 1)) / Math.log2(SIZE_CONFIG.maxChannels);
const width = SIZE_CONFIG.minWidth + normalizedChannels * (SIZE_CONFIG.maxWidth - SIZE_CONFIG.minWidth);
// Height based on layer type and parameters
let height: number;
if (node.level === 1) {
height = SIZE_CONFIG.macroHeight;
} else if (node.level === 2) {
height = SIZE_CONFIG.stageHeight;
} else {
// For individual layers, use parameter count
const normalizedParams = Math.log10(Math.max(params, 1)) / Math.log10(SIZE_CONFIG.maxParams);
height = SIZE_CONFIG.minHeight + normalizedParams * (SIZE_CONFIG.maxHeight - SIZE_CONFIG.minHeight);
}
return {
width: Math.max(SIZE_CONFIG.minWidth, width),
height: Math.max(SIZE_CONFIG.minHeight, height),
depth: SIZE_CONFIG.baseDepth,
};
}
// ============================================================================
// Geometry Generators
// ============================================================================
export type LayerGeometryType =
| 'box' // Default, linear layers
| 'prism' // Convolution layers
| 'plate' // Normalization layers
| 'cylinder' // Activation layers
| 'hexagon' // Attention layers
| 'pyramid' // Output/head layers
| 'rounded-box' // Pooling layers
| 'container'; // Group containers
/**
* Get geometry type for a layer category
*/
export function getGeometryType(category: string): LayerGeometryType {
const mapping: Record<string, LayerGeometryType> = {
convolution: 'prism',
linear: 'box',
normalization: 'plate',
activation: 'cylinder',
pooling: 'rounded-box',
recurrent: 'hexagon',
attention: 'hexagon',
embedding: 'box',
regularization: 'plate',
reshape: 'plate',
output: 'pyramid',
encoder: 'container',
decoder: 'container',
stage: 'container',
group: 'container',
};
return mapping[category] || 'box';
}
/**
* Create box geometry (default)
*/
export function createBoxGeometry(dims: LayerDimensions): THREE.BufferGeometry {
return new THREE.BoxGeometry(dims.depth, dims.height, dims.width);
}
/**
* Create prism geometry (for convolution layers)
*/
export function createPrismGeometry(dims: LayerDimensions): THREE.BufferGeometry {
// Slightly tapered box to indicate transformation
const shape = new THREE.Shape();
const hw = dims.width / 2;
const hd = dims.depth / 2;
const taper = 0.1;
shape.moveTo(-hd, -hw * (1 + taper));
shape.lineTo(hd, -hw);
shape.lineTo(hd, hw);
shape.lineTo(-hd, hw * (1 + taper));
shape.closePath();
const extrudeSettings = {
depth: dims.height,
bevelEnabled: false,
};
const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
geometry.rotateX(-Math.PI / 2);
geometry.translate(0, dims.height / 2, 0);
return geometry;
}
/**
* Create thin plate geometry (for normalization/reshape)
*/
export function createPlateGeometry(dims: LayerDimensions): THREE.BufferGeometry {
return new THREE.BoxGeometry(dims.depth * 0.3, dims.height, dims.width);
}
/**
* Create cylinder geometry (for activation layers)
*/
export function createCylinderGeometry(dims: LayerDimensions): THREE.BufferGeometry {
return new THREE.CylinderGeometry(
dims.width / 2.5,
dims.width / 2.5,
dims.height,
16
);
}
/**
* Create hexagonal prism (for attention/recurrent layers)
*/
export function createHexagonGeometry(dims: LayerDimensions): THREE.BufferGeometry {
const shape = new THREE.Shape();
const radius = dims.width / 2;
for (let i = 0; i < 6; i++) {
const angle = (Math.PI / 3) * i - Math.PI / 2;
const x = Math.cos(angle) * radius;
const y = Math.sin(angle) * radius;
if (i === 0) {
shape.moveTo(x, y);
} else {
shape.lineTo(x, y);
}
}
shape.closePath();
const extrudeSettings = {
depth: dims.depth,
bevelEnabled: false,
};
const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
geometry.rotateY(Math.PI / 2);
geometry.rotateZ(Math.PI / 2);
return geometry;
}
/**
* Create pyramid geometry (for output layers)
*/
export function createPyramidGeometry(dims: LayerDimensions): THREE.BufferGeometry {
return new THREE.ConeGeometry(dims.width / 2, dims.height, 4);
}
/**
* Create rounded box geometry (for pooling layers)
*/
export function createRoundedBoxGeometry(dims: LayerDimensions): THREE.BufferGeometry {
// Simple approach: regular box with slight modifications
// For true rounded corners, use RoundedBoxGeometry from drei or custom
const geometry = new THREE.BoxGeometry(
dims.depth,
dims.height,
dims.width,
2, 2, 2
);
return geometry;
}
/**
* Create container geometry (for groups - wireframe style)
*/
export function createContainerGeometry(dims: LayerDimensions): THREE.BufferGeometry {
return new THREE.BoxGeometry(
dims.depth * 2,
dims.height,
dims.width * 1.5
);
}
/**
* Main geometry factory
*/
export function createLayerGeometry(
node: HierarchyNode,
dims?: LayerDimensions
): THREE.BufferGeometry {
const dimensions = dims || calculateLayerDimensions(node);
const geometryType = getGeometryType(node.category);
switch (geometryType) {
case 'prism':
return createPrismGeometry(dimensions);
case 'plate':
return createPlateGeometry(dimensions);
case 'cylinder':
return createCylinderGeometry(dimensions);
case 'hexagon':
return createHexagonGeometry(dimensions);
case 'pyramid':
return createPyramidGeometry(dimensions);
case 'rounded-box':
return createRoundedBoxGeometry(dimensions);
case 'container':
return createContainerGeometry(dimensions);
case 'box':
default:
return createBoxGeometry(dimensions);
}
}
// ============================================================================
// Material Generators
// ============================================================================
export interface LayerMaterialOptions {
color: string;
opacity?: number;
wireframe?: boolean;
selected?: boolean;
hovered?: boolean;
isContainer?: boolean;
}
/**
* Create material for layer visualization
*/
export function createLayerMaterial(options: LayerMaterialOptions): THREE.Material {
const { color, opacity = 1, wireframe = false, selected = false, hovered = false, isContainer = false } = options;
if (isContainer) {
return new THREE.MeshBasicMaterial({
color: new THREE.Color(color),
transparent: true,
opacity: 0.15,
wireframe: true,
});
}
const baseColor = new THREE.Color(color);
if (selected) {
baseColor.multiplyScalar(1.3);
} else if (hovered) {
baseColor.multiplyScalar(1.15);
}
return new THREE.MeshStandardMaterial({
color: baseColor,
transparent: opacity < 1,
opacity,
wireframe,
metalness: 0.1,
roughness: 0.7,
emissive: selected ? baseColor.clone().multiplyScalar(0.2) : undefined,
});
}
/**
* Create edge/outline material
*/
export function createEdgeMaterial(color: string): THREE.LineBasicMaterial {
return new THREE.LineBasicMaterial({
color: new THREE.Color(color),
linewidth: 2,
});
}
// ============================================================================
// Geometry Cache (for InstancedMesh optimization)
// ============================================================================
const geometryCache = new Map<string, THREE.BufferGeometry>();
export function getCachedGeometry(
node: HierarchyNode,
dims: LayerDimensions
): THREE.BufferGeometry {
const key = `${node.category}_${dims.width.toFixed(2)}_${dims.height.toFixed(2)}_${dims.depth.toFixed(2)}`;
if (!geometryCache.has(key)) {
geometryCache.set(key, createLayerGeometry(node, dims));
}
return geometryCache.get(key)!;
}
export function clearGeometryCache(): void {
geometryCache.forEach(geometry => geometry.dispose());
geometryCache.clear();
}
|