πŸ“¦ RightNow-AI / RightNow-Tile

πŸ“„ ARCHITECTURE.md Β· 474 lines
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# RightNow Tile - Enhanced CUDA to cuTile Transpiler

## Architecture Overview

RightNow Tile is a production-grade transpiler that converts CUDA SIMT (Single Instruction, Multiple Threads) kernels to cuTile Python code optimized for NVIDIA Blackwell GPUs.

```
CUDA Source
    β”‚
    β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    ANALYSIS LAYER                           β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚   AST    │──▢│ Enhanced │──▢│ Semantic  │──▢│ Pattern β”‚ β”‚
β”‚  β”‚Extractor β”‚   β”‚  Parser  β”‚   β”‚ Analyzer  β”‚   β”‚Detector β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚                       β”‚        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”        β”‚       β”‚
β”‚                       └───────▢│  Memory   β”‚β”€β”€β”€β”€β”€β”€β”€β”€β”˜       β”‚
β”‚                                β”‚ Analyzer  β”‚                β”‚
β”‚                                β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
                              β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                 BLACKWELL GPU TARGET                        β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚    IR    │──▢│    IR    │──▢│ Template │──▢│ cuTile  β”‚  β”‚
β”‚  β”‚ Builder  β”‚   β”‚Optimizer β”‚   β”‚ CodeGen  β”‚   β”‚ Output  β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚                       β–²              β”‚                      β”‚
β”‚                       β”‚        β”Œβ”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”               β”‚
β”‚            optimization hints  β”‚Diagnosticsβ”‚               β”‚
β”‚                                β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜               β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

## Directory Structure

```
lib/
β”œβ”€β”€ transpiler.ts              # Main entry point
β”œβ”€β”€ parser/                    # Enhanced parsing
β”‚   β”œβ”€β”€ intrinsics.ts          # CUDA intrinsics database (~100)
β”‚   β”œβ”€β”€ cuda-parser.ts         # Enhanced parser with semantic analysis
β”‚   └── index.ts
β”œβ”€β”€ ast/                       # AST and analysis
β”‚   β”œβ”€β”€ types.ts               # Type definitions
β”‚   β”œβ”€β”€ extractor.ts           # Kernel extraction
β”‚   β”œβ”€β”€ semantic-analyzer.ts   # Data flow analysis
β”‚   β”œβ”€β”€ memory-analyzer.ts     # Memory pattern analysis
β”‚   └── index.ts
β”œβ”€β”€ patterns/                  # Pattern detection
β”‚   β”œβ”€β”€ types.ts               # Pattern types and variants
β”‚   β”œβ”€β”€ matcher.ts             # Pattern orchestrator
β”‚   └── matchers/
β”‚       β”œβ”€β”€ elementwise.ts     # Elementwise operations
β”‚       β”œβ”€β”€ gemm.ts            # Matrix multiplication
β”‚       β”œβ”€β”€ reduction.ts       # Parallel reductions
β”‚       β”œβ”€β”€ scan.ts            # Prefix sums
β”‚       β”œβ”€β”€ stencil.ts         # Neighbor computations
β”‚       β”œβ”€β”€ histogram.ts       # Histogram patterns
β”‚       β”œβ”€β”€ sparse.ts          # Sparse matrix operations
β”‚       β”œβ”€β”€ attention.ts       # Flash Attention, MHA
β”‚       β”œβ”€β”€ fused.ts           # Fused kernel patterns
β”‚       β”œβ”€β”€ fft.ts             # FFT patterns
β”‚       β”œβ”€β”€ convolution.ts     # CNN convolutions
β”‚       β”œβ”€β”€ sorting.ts         # Sorting algorithms
β”‚       β”œβ”€β”€ pooling.ts         # Pooling operations
β”‚       β”œβ”€β”€ normalization.ts   # LayerNorm, BatchNorm, etc.
β”‚       β”œβ”€β”€ embedding.ts       # Embedding lookup
β”‚       β”œβ”€β”€ rope.ts            # Rotary Position Embedding
β”‚       β”œβ”€β”€ kvcache.ts         # KV cache operations
β”‚       └── quantization.ts    # INT8/INT4/FP8 quantization
β”œβ”€β”€ ir/                        # Intermediate representation
β”‚   β”œβ”€β”€ types.ts               # Enhanced IR types
β”‚   β”œβ”€β”€ builder.ts             # IR construction
β”‚   β”œβ”€β”€ optimizer.ts           # Tile optimization
β”‚   └── index.ts
β”œβ”€β”€ codegen/                   # Code generation
β”‚   β”œβ”€β”€ generator.ts           # Generic code generator
β”‚   β”œβ”€β”€ templates/             # Variant-specific templates
β”‚   β”‚   β”œβ”€β”€ reduction.ts       # Reduction variants
β”‚   β”‚   β”œβ”€β”€ stencil.ts         # Stencil variants
β”‚   β”‚   β”œβ”€β”€ gemm.ts            # GEMM variants
β”‚   β”‚   β”œβ”€β”€ scan.ts            # Scan variants
β”‚   β”‚   β”œβ”€β”€ histogram.ts       # Histogram variants
β”‚   β”‚   β”œβ”€β”€ sparse.ts          # SpMV/SpMM variants
β”‚   β”‚   β”œβ”€β”€ attention.ts       # Flash Attention templates
β”‚   β”‚   β”œβ”€β”€ fused.ts           # Fused kernel templates
β”‚   β”‚   β”œβ”€β”€ fft.ts             # FFT templates
β”‚   β”‚   β”œβ”€β”€ convolution.ts     # Convolution templates
β”‚   β”‚   β”œβ”€β”€ sorting.ts         # Sorting templates
β”‚   β”‚   β”œβ”€β”€ pooling.ts         # Pooling templates
β”‚   β”‚   β”œβ”€β”€ normalization.ts   # Normalization templates
β”‚   β”‚   β”œβ”€β”€ embedding.ts       # Embedding templates
β”‚   β”‚   β”œβ”€β”€ rope.ts            # RoPE templates
β”‚   β”‚   β”œβ”€β”€ kvcache.ts         # KV cache templates
β”‚   β”‚   β”œβ”€β”€ quantization.ts    # Quantization templates
β”‚   β”‚   └── index.ts
β”‚   └── index.ts
└── validation/                # Validation and diagnostics
    β”œβ”€β”€ validator.ts           # Semantic validation
    β”œβ”€β”€ diagnostics.ts         # Error/warning system
    └── index.ts
```

## Components

### 1. Parser Enhancement (`lib/parser/`)

#### CUDA Intrinsics Database (`intrinsics.ts`)
Comprehensive database of 150+ CUDA intrinsics organized by category:

| Category | Examples | Pattern Hints |
|----------|----------|---------------|
| Warp Shuffle | `__shfl_down_sync`, `__shfl_xor_sync` | Reduction, Scan |
| Warp Vote | `__ballot_sync`, `__any_sync` | Reduction |
| Warp Reduce | `__reduce_add_sync`, `__reduce_max_sync` | Reduction |
| Atomic | `atomicAdd`, `atomicMax`, `atomicCAS` | Reduction, Histogram |
| Sync | `__syncthreads`, `__syncwarp` | All patterns |
| Math | `__fmaf`, `__expf`, `__rsqrtf`, `__sincosf` | Elementwise, Attention, RoPE |
| Memory | `__ldg`, `__ldcs` | All patterns |
| Type Conversion | `__float2half`, `__half2float`, `__float2int_rn` | Quantization |
| Tensor Core | `wmma::load`, `wmma::store`, `wmma::mma` | GEMM, Attention |
| Extended Math | `tanhf`, `erff`, `roundf`, `truncf` | Normalization, Activation |

#### Enhanced Parser (`cuda-parser.ts`)
Advanced parsing capabilities:
- **Intrinsic Call Detection**: Identifies all CUDA intrinsic usage
- **Index Pattern Analysis**: Classifies memory access patterns (linear, 2D, strided, indirect)
- **Warp Operation Detection**: Finds warp-level primitives
- **Loop Analysis**: Detects stride halving/doubling, nested loops
- **Reduction Pattern Detection**: Identifies accumulation patterns
- **Shared Memory Analysis**: Tracks declarations and bank conflicts

### 2. Semantic Analysis (`lib/ast/semantic-analyzer.ts`)

Performs deep semantic analysis:

```typescript
interface SemanticAnalysisResult {
  reductionVariables: ReductionVariable[];   // sum, max, min, prod
  inductionVariables: InductionVariable[];   // Loop counters
  accessPatterns: AccessPatternClassification[];
  dataFlow: DataFlowInfo;                    // Dependencies
  hasBarrierDivergence: boolean;             // Deadlock risk
  possibleRaces: RaceCondition[];            // Race detection
  parallelismType: ParallelismType;
  computeIntensity: ComputeIntensityMetrics;
}
```

**Key Analyses:**
- Reduction variable detection (`sum += x`, `max = max(max, x)`)
- Data dependency analysis (RAW, WAR, WAW)
- Race condition detection in shared memory
- Barrier divergence checking
- Compute intensity estimation (FLOPS/byte)

### 3. Memory Analysis (`lib/ast/memory-analyzer.ts`)

Analyzes memory access patterns for optimization:

```typescript
interface MemoryAnalysisResult {
  globalMemory: GlobalMemoryAnalysis;        // Coalescing score
  sharedMemory: SharedMemoryAnalysis;        // Bank conflicts
  registers: RegisterAnalysis;               // Spilling risk
  tileRecommendation: TileRecommendation;    // Optimal sizes
  accessSummary: AccessSummary;              // Locality info
  optimizationHints: MemoryOptimizationHint[];
}
```

**Capabilities:**
- Coalescing efficiency scoring (0-100%)
- Bank conflict risk assessment
- Register pressure estimation
- Tile size recommendations per pattern
- Vectorization opportunities

### 4. Pattern Detection (`lib/patterns/`)

#### Supported Patterns (18 archetypes, 60+ variants)

**Core Patterns:**
| Pattern | Description | Variants |
|---------|-------------|----------|
| **Elementwise** | Per-element operations | `simple`, `vectorized` |
| **GEMM** | Matrix multiplication | `naive_gemm`, `tiled_gemm`, `register_blocked` |
| **Reduction** | Parallel aggregation | `tree_reduction`, `warp_shuffle`, `multi_block`, `segmented` |
| **Scan** | Prefix sums | `inclusive_scan`, `exclusive_scan`, `segmented_scan` |
| **Stencil** | Neighbor computations | `stencil_1d_3pt`, `stencil_1d_5pt`, `stencil_2d_5pt`, `stencil_2d_9pt`, `stencil_3d` |
| **Histogram** | Binned counting | `histogram_atomic`, `histogram_privatized`, `histogram_weighted`, `histogram_2d` |
| **Sparse** | Sparse matrix ops | `spmv_csr`, `spmv_csr_warp`, `spmv_coo`, `spmv_ell`, `spmm_csr`, `sddmm` |

**ML/DL Patterns:**
| Pattern | Description | Variants |
|---------|-------------|----------|
| **Convolution** | 1D/2D/3D convolutions | `conv_1d`, `conv_2d`, `conv_3d`, `conv_depthwise`, `conv_grouped`, `conv_winograd`, `conv_im2col`, `conv_implicit_gemm` |
| **Pooling** | Spatial pooling | `max_pool_2d`, `avg_pool_2d`, `global_avg_pool`, `global_max_pool`, `adaptive_avg_pool`, `adaptive_max_pool` |
| **Normalization** | Normalization layers | `layernorm`, `rmsnorm`, `batchnorm`, `groupnorm`, `instancenorm` |
| **Fused** | Fused operations | `matmul_activation`, `matmul_bias_activation`, `conv_batchnorm`, `layernorm_residual` |

**LLM-Specific Patterns:**
| Pattern | Description | Variants |
|---------|-------------|----------|
| **Attention** | Attention mechanisms | `flash_attention`, `flash_attention_v2`, `multi_head_attention`, `causal_attention`, `cross_attention` |
| **RoPE** | Rotary position embedding | `rope_standard`, `rope_neox`, `rope_cached` |
| **KV Cache** | Key-value cache ops | `kvcache_append`, `kvcache_paged`, `kvcache_prefix`, `kvcache_gqa` |
| **Embedding** | Embedding operations | `embedding_lookup`, `embedding_bag`, `positional_embedding` |
| **Quantization** | Quantization kernels | `quant_int8`, `quant_int4`, `quant_fp8`, `quantize`, `dequantize` |

**Specialized Patterns:**
| Pattern | Description | Variants |
|---------|-------------|----------|
| **FFT** | Fast Fourier Transform | `fft_radix2`, `fft_radix4`, `fft_radix8`, `inverse_fft`, `real_fft` |
| **Sorting** | Sorting algorithms | `bitonic_sort`, `bitonic_sort_shared`, `radix_sort`, `merge_sort` |

#### Evidence-Based Matching
Each pattern matcher uses weighted evidence:

```typescript
// Example: Reduction detection
if (hasStrideHalving) {
  addEvidence(evidence, 'stride_halving', 0.35, 'Stride halving detected');
}
if (hasWarpShuffle) {
  addEvidence(evidence, 'warp_shuffle', 0.15, 'Warp shuffle instructions');
}
// Negative evidence
if (hasMatrixMultiply) {
  addEvidence(evidence, 'matrix_multiply', -0.20, 'Likely GEMM');
}
```

### 5. IR Optimization (`lib/ir/optimizer.ts`)

Optimizes tile configurations based on:
- Pattern archetype and variant
- Memory analysis results
- Architecture constraints (shared memory, registers)

**Tile Configurations by Pattern:**

| Pattern | Default Config | Optimization |
|---------|----------------|--------------|
| GEMM | 128x128x32 | Register blocking, pipeline stages |
| Reduction | 256 threads | Warp shuffle, multi-block |
| Stencil | 16x16 tiles | Halo caching |
| Histogram | 256 threads | Privatization |

### 6. Code Generation (`lib/codegen/`)

#### Variant-Specific Templates
Templates for optimized code generation across all 18 archetypes:

**Core Templates:**
- `generateTreeReduction()` - Shared memory tree reduction
- `generateWarpShuffleReduction()` - Warp shuffle intrinsics
- `generateStencil2D5Point()` - 2D cross stencil
- `generateTiledGemm()` - Tiled matrix multiplication

**ML/DL Templates:**
- `generateConv2D()` - 2D convolution with various algorithms
- `generateMaxPool2D()` / `generateAvgPool2D()` - Pooling operations
- `generateLayerNorm()` / `generateRMSNorm()` - Normalization layers
- `generateFusedMatmulActivation()` - Fused operations

**LLM-Specific Templates:**
- `generateFlashAttention()` - Memory-efficient attention with online softmax
- `generateMultiHeadAttention()` - Standard MHA
- `generateRoPEStandard()` / `generateRoPENeoX()` - Rotary embeddings
- `generateKVCacheAppend()` / `generateKVCachePaged()` - KV cache operations
- `generateEmbeddingLookup()` - Embedding table lookup
- `generateQuantInt8()` / `generateQuantInt4()` - Quantization kernels

**Specialized Templates:**
- `generateBitonicSort()` / `generateRadixSort()` - Sorting algorithms
- `generateFFTRadix2()` / `generateFFTRadix4()` - FFT operations
- `generateSpMVCSR()` / `generateSpMMCSR()` - Sparse operations

#### Type Mapping
CUDA to cuTile type conversion:

```typescript
const TYPE_MAP = {
  'float': 'ct.float32',
  'double': 'ct.float64',
  'half': 'ct.float16',
  'int': 'ct.int32',
  'int8_t': 'ct.int8',
  // ... more types
};
```

### 7. Diagnostics System (`lib/validation/diagnostics.ts`)

Comprehensive error/warning reporting:

**Diagnostic Codes:**

| Code | Severity | Category | Description |
|------|----------|----------|-------------|
| E100-E104 | Error | Parse | Parsing errors |
| E300-E301 | Error | Correctness | Race conditions, barrier divergence |
| W200-W204 | Warning | Pattern | Low confidence, ambiguous patterns |
| W300-W303 | Warning | Semantic | Dependencies, missing sync |
| W400-W403 | Warning | Memory | Poor coalescing, bank conflicts |
| I400-I402 | Info | Performance | Optimization suggestions |
| I600-I603 | Info | Performance | Performance hints |

## Usage

### Basic Transpilation

```typescript
import { transpile } from './lib/transpiler';

const cudaCode = `
__global__ void reduce(float* input, float* output, int n) {
    __shared__ float sdata[256];
    int tid = threadIdx.x;
    int i = blockIdx.x * blockDim.x + threadIdx.x;

    sdata[tid] = (i < n) ? input[i] : 0;
    __syncthreads();

    for (int s = blockDim.x / 2; s > 0; s >>= 1) {
        if (tid < s) {
            sdata[tid] += sdata[tid + s];
        }
        __syncthreads();
    }

    if (tid == 0) atomicAdd(output, sdata[0]);
}
`;

const result = await transpile(cudaCode);

console.log(result.pattern.archetype);  // 'reduction'
console.log(result.variant);            // 'tree_reduction' or 'multi_block'
console.log(result.pattern.confidence); // 0.85
console.log(result.tileCode);           // Generated cuTile Python
console.log(result.diagnostics);        // Any warnings/hints
```

### Enhanced Result

```typescript
interface EnhancedTranspileResult {
  tileCode: string;                      // Generated code
  pattern: PatternMatch;                 // Detected pattern
  variant?: PatternVariant;              // Specific variant
  ir: KernelIR;                          // Basic IR
  enhancedIR?: EnhancedKernelIR;         // Optimized IR
  semanticAnalysis?: SemanticAnalysisResult;
  memoryAnalysis?: MemoryAnalysisResult;
  diagnostics?: Diagnostic[];
  validation: ValidationResult;
}
```

## Pattern Detection Examples

### Core Patterns

```cuda
// Detected as 'reduction' with variant 'warp_shuffle'
for (int offset = 16; offset > 0; offset /= 2) {
    val += __shfl_down_sync(0xffffffff, val, offset);
}
```

```cuda
// Detected as 'stencil' with variant 'stencil_2d_5pt'
out[i] = 0.25f * (in[i-1] + in[i+1] + in[i-width] + in[i+width]);
```

### ML/DL Patterns

```cuda
// Detected as 'convolution' with variant 'conv_2d'
for (int kh = 0; kh < kernel_h; kh++) {
    for (int kw = 0; kw < kernel_w; kw++) {
        sum += input[...] * weight[...];
    }
}
```

```cuda
// Detected as 'normalization' with variant 'layernorm'
float mean = 0, var = 0;
for (int i = threadIdx.x; i < D; i += blockDim.x) mean += x[row * D + i];
// ... compute variance, normalize, scale + shift
```

### LLM-Specific Patterns

```cuda
// Detected as 'attention' with variant 'flash_attention'
__global__ void flash_attention(float* Q, float* K, float* V, float* O, ...) {
    extern __shared__ float smem[];
    // Q @ K^T with online softmax, then @ V
}
```

```cuda
// Detected as 'rope' with variant 'rope_standard'
float cos_val = cos_cache[pos * head_dim + d];
float sin_val = sin_cache[pos * head_dim + d];
out[idx] = x[idx] * cos_val - x[idx + half_dim] * sin_val;
out[idx + half_dim] = x[idx] * sin_val + x[idx + half_dim] * cos_val;
```

```cuda
// Detected as 'quantization' with variant 'quant_int8'
float val = input[idx] / scale;
val = fmaxf(-128.0f, fminf(127.0f, roundf(val)));
output[idx] = (int8_t)val;
```

### Specialized Patterns

```cuda
// Detected as 'sparse' with variant 'spmv_csr'
for (int j = row_ptr[row]; j < row_ptr[row + 1]; j++) {
    sum += values[j] * x[col_idx[j]];
}
```

```cuda
// Detected as 'sorting' with variant 'bitonic_sort'
for (int k = 2; k <= n; k *= 2) {
    for (int j = k / 2; j > 0; j /= 2) {
        // Compare and swap pairs
    }
}
```

## Performance Considerations

### Memory Coalescing
The transpiler analyzes access patterns and warns about:
- Strided access (< 50% efficiency)
- Random/indirect access (< 10% efficiency)
- Non-aligned access

### Bank Conflicts
Shared memory bank conflict detection:
- Stride-based conflicts (multiples of 32)
- Column-major access in 2D arrays
- Suggests padding strategies

### Tile Size Optimization
Automatic tile size selection based on:
- Pattern type (GEMM needs larger tiles)
- Shared memory capacity (48KB default)
- Register pressure
- Occupancy targets

## Future Enhancements

- [ ] Full tree-sitter CUDA parser integration
- [x] More pattern variants (18 archetypes, 60+ variants)
- [x] LLM-specific patterns (attention, RoPE, KV cache, quantization)
- [x] ML/DL patterns (convolution, pooling, normalization)
- [ ] Auto-tuning for tile sizes
- [ ] Multi-kernel fusion detection
- [ ] Performance modeling and prediction
- [ ] Tensor core pattern optimization
- [ ] Cooperative groups support