Skip to main content
Glama
apolosan

Design Patterns MCP Server

by apolosan
compute-kernel.json9.82 kB
{ "id": "compute-kernel", "name": "Compute Kernel", "category": "Concurrency", "description": "The same calculation many times in parallel, differing by integer parameters", "when_to_use": "Parallel computation\nSIMD operations\nGPU computing\nData processing", "benefits": "Parallel execution\nPerformance scaling\nResource utilization\nSIMD optimization", "drawbacks": "Synchronization overhead\nMemory bandwidth\nLoad balancing\nDebugging complexity", "use_cases": "Matrix operations\nImage processing\nScientific computing\nMachine learning", "complexity": "High", "tags": ["concurrency", "compute-kernel", "parallel-computing", "simd", "gpu"], "examples": { "typescript": { "language": "typescript", "code": "// Compute Kernel Pattern\n// Same calculation performed many times in parallel with different parameters\n\n// Kernel interface - defines the computation to be parallelized\ninterface ComputeKernel<TInput, TResult> {\n execute(input: TInput, index: number): TResult;\n getWorkSize(input: TInput): number;\n}\n\n// Kernel executor - manages parallel execution\nclass KernelExecutor {\n private workers: Worker[] = [];\n private isRunning: boolean = false;\n\n constructor(private numWorkers: number = navigator.hardwareConcurrency || 4) {\n this.createWorkers();\n }\n\n private createWorkers(): void {\n for (let i = 0; i < this.numWorkers; i++) {\n const worker = new Worker('/kernel-worker.js');\n this.workers.push(worker);\n }\n }\n\n async execute<TInput, TResult>(\n kernel: ComputeKernel<TInput, TResult>,\n input: TInput\n ): Promise<TResult[]> {\n if (this.isRunning) {\n throw new Error('Kernel executor is already running');\n }\n\n this.isRunning = true;\n const workSize = kernel.getWorkSize(input);\n const results: TResult[] = new Array(workSize);\n\n try {\n // Distribute work among workers\n const workPerWorker = Math.ceil(workSize / this.numWorkers);\n const promises: Promise<void>[] = [];\n\n for (let workerIndex = 0; workerIndex < this.numWorkers; workerIndex++) {\n const startIndex = workerIndex * workPerWorker;\n const endIndex = Math.min(startIndex + workPerWorker, workSize);\n\n if (startIndex >= workSize) break;\n\n const promise = this.executeOnWorker(\n kernel,\n input,\n startIndex,\n endIndex,\n results\n );\n promises.push(promise);\n }\n\n await Promise.all(promises);\n return results;\n } finally {\n this.isRunning = false;\n }\n }\n\n private async executeOnWorker<TInput, TResult>(\n kernel: ComputeKernel<TInput, TResult>,\n input: TInput,\n startIndex: number,\n endIndex: number,\n results: TResult[]\n ): Promise<void> {\n return new Promise((resolve, reject) => {\n // Find available worker (simplified - in real implementation use worker pool)\n const worker = this.workers[0]; // Simplified for example\n\n const message = {\n type: 'execute',\n kernelCode: kernel.constructor.toString(),\n input: input,\n startIndex,\n endIndex\n };\n\n worker.postMessage(message);\n\n worker.onmessage = (e) => {\n const { results: workerResults, startIndex: workerStart } = e.data;\n for (let i = 0; i < workerResults.length; i++) {\n results[workerStart + i] = workerResults[i];\n }\n resolve();\n };\n\n worker.onerror = (error) => {\n reject(error);\n };\n });\n }\n\n dispose(): void {\n this.workers.forEach(worker => worker.terminate());\n this.workers = [];\n }\n}\n\n// Example: Matrix multiplication kernel\nclass MatrixMultiplicationKernel implements ComputeKernel<MatrixData, number> {\n execute(input: MatrixData, index: number): number {\n const { a, b, size } = input;\n const row = Math.floor(index / size);\n const col = index % size;\n\n let sum = 0;\n for (let k = 0; k < size; k++) {\n sum += a[row * size + k] * b[k * size + col];\n }\n return sum;\n }\n\n getWorkSize(input: MatrixData): number {\n return input.size * input.size;\n }\n}\n\ninterface MatrixData {\n a: number[];\n b: number[];\n size: number;\n}\n\n// Usage\nconst executor = new KernelExecutor(4);\nconst kernel = new MatrixMultiplicationKernel();\n\nconst matrixA = [1, 2, 3, 4, 5, 6, 7, 8, 9];\nconst matrixB = [9, 8, 7, 6, 5, 4, 3, 2, 1];\n\nconst input: MatrixData = {\n a: matrixA,\n b: matrixB,\n size: 3\n};\n\nexecutor.execute(kernel, input).then(result => {\n console.log('Matrix multiplication result:', result);\n executor.dispose();\n});\n\n// Example: Image processing kernel (blur effect)\nclass BlurKernel implements ComputeKernel<ImageData, number> {\n execute(input: ImageData, index: number): number {\n const { data, width, height } = input;\n const x = index % width;\n const y = Math.floor(index / width);\n\n if (x === 0 || x === width - 1 || y === 0 || y === height - 1) {\n return data[index]; // Keep edge pixels unchanged\n }\n\n // Simple 3x3 blur kernel\n let sum = 0;\n let count = 0;\n for (let dy = -1; dy <= 1; dy++) {\n for (let dx = -1; dx <= 1; dx++) {\n const nx = x + dx;\n const ny = y + dy;\n if (nx >= 0 && nx < width && ny >= 0 && ny < height) {\n sum += data[(ny * width + nx) * 4]; // Red channel\n count++;\n }\n }\n }\n return sum / count;\n }\n\n getWorkSize(input: ImageData): number {\n return input.width * input.height;\n }\n}\n\n// Example: Particle simulation kernel\nclass ParticleKernel implements ComputeKernel<ParticleData, ParticleState> {\n execute(input: ParticleData, index: number): ParticleState {\n const particle = input.particles[index];\n const { deltaTime, gravity, bounds } = input;\n\n // Apply gravity\n particle.velocity.y += gravity * deltaTime;\n\n // Update position\n particle.position.x += particle.velocity.x * deltaTime;\n particle.position.y += particle.velocity.y * deltaTime;\n\n // Bounce off boundaries\n if (particle.position.x < bounds.left || particle.position.x > bounds.right) {\n particle.velocity.x *= -0.8; // Damping\n particle.position.x = Math.max(bounds.left, Math.min(bounds.right, particle.position.x));\n }\n if (particle.position.y < bounds.top || particle.position.y > bounds.bottom) {\n particle.velocity.y *= -0.8; // Damping\n particle.position.y = Math.max(bounds.top, Math.min(bounds.bottom, particle.position.y));\n }\n\n return particle;\n }\n\n getWorkSize(input: ParticleData): number {\n return input.particles.length;\n }\n}\n\ninterface ParticleState {\n position: { x: number; y: number };\n velocity: { x: number; y: number };\n}\n\ninterface ParticleData {\n particles: ParticleState[];\n deltaTime: number;\n gravity: number;\n bounds: { left: number; top: number; right: number; bottom: number };\n}\n\n// Example: Ray tracing kernel\nclass RayTracingKernel implements ComputeKernel<SceneData, Color> {\n execute(input: SceneData, index: number): Color {\n const { width, height, camera, objects } = input;\n const x = index % width;\n const y = Math.floor(index / width);\n\n // Generate ray from camera through pixel\n const ray = this.generateRay(camera, x, y, width, height);\n\n // Trace ray through scene\n return this.traceRay(ray, objects, 0);\n }\n\n getWorkSize(input: SceneData): number {\n return input.width * input.height;\n }\n\n private generateRay(camera: Camera, x: number, y: number, width: number, height: number): Ray {\n // Camera ray generation logic\n return { origin: camera.position, direction: { x: 0, y: 0, z: 1 } }; // Simplified\n }\n\n private traceRay(ray: Ray, objects: SceneObject[], depth: number): Color {\n if (depth > 5) return { r: 0, g: 0, b: 0 }; // Max recursion\n\n // Find closest intersection\n let closest: Intersection | null = null;\n for (const obj of objects) {\n const intersection = this.intersectRayObject(ray, obj);\n if (intersection && (!closest || intersection.distance < closest.distance)) {\n closest = intersection;\n }\n }\n\n if (!closest) return { r: 0, g: 0, b: 0 }; // Background\n\n // Simple lighting calculation\n const light = { r: 255, g: 255, b: 255 };\n const intensity = Math.max(0, closest.normal.dot({ x: 0, y: 1, z: 0 }));\n return {\n r: Math.floor(closest.color.r * intensity),\n g: Math.floor(closest.color.g * intensity),\n b: Math.floor(closest.color.b * intensity)\n };\n }\n\n private intersectRayObject(ray: Ray, obj: SceneObject): Intersection | null {\n // Ray-object intersection logic (simplified)\n return null;\n }\n}\n\ninterface Color {\n r: number;\n g: number;\n b: number;\n}\n\ninterface Ray {\n origin: { x: number; y: number; z: number };\n direction: { x: number; y: number; z: number };\n}\n\ninterface SceneObject {\n type: 'sphere' | 'plane';\n position: { x: number; y: number; z: number };\n color: Color;\n}\n\ninterface Intersection {\n distance: number;\n position: { x: number; y: number; z: number };\n normal: { x: number; y: number; z: number };\n color: Color;\n}\n\ninterface Camera {\n position: { x: number; y: number; z: number };\n}\n\ninterface SceneData {\n width: number;\n height: number;\n camera: Camera;\n objects: SceneObject[];\n}\n\n// Benefits of Compute Kernel Pattern:\n// 1. Efficient parallel execution\n// 2. Natural fit for GPU computing\n// 3. Scalable with hardware capabilities\n// 4. Optimal for data-parallel problems\n// 5. High performance for compute-intensive tasks" } } }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/apolosan/design_patterns_mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server