Berkeley AI Research、Apple Silicon向け最適化手法「K-Search」を公開
Berkeley AI Research は CUDA から MLX への移行知見を基に、Apple Silicon で FlashAttention や Mamba を高速化する手法 K-Search を発表した。
AI深層分析を開く2026年7月30日 09:38
AI深層分析
キーポイント
CUDA から MLX への知識転送フレームワークの確立
IBM Research は Berkeley Sky Lab が開発した K-Search を基盤とし、既存の CUDA カーネルの最適化ノウハウを Apple Silicon の MLX フレームワークへ自動的に翻訳・適応させる層を開発した。
Apple Silicon における高性能な計算結果
同社の手法により、FlashAttention と同等の性能(97%)を達成し、Mamba SSM のプリフィル処理においては約 20 倍の高速化を実現したと発表した。
アーキテクチャ固有の最適化戦略への転換
単なる命令列のコピーではなく、CUDA の最適化知識を Apple Silicon に適した MLX 固有の戦略へと翻訳する構造化された手法を採用している。
CUDA から MLX への自動翻訳層の実装
既存の CUDA カーネルを知識ベースとして活用し、Apple Silicon 向けに高品質な MLX カーネルへ適応させる構造化された翻訳レイヤーを開発した。これにより、ゼロから再構築するのではなく、数十年のカーネル専門知見を自動的に転送可能となった。
MLX 環境における性能向上の実証
Apple Silicon 上でネイティブ MLX Attention カーネルに対し 0.97 倍、mlx-lm 実装の Mamba SSM カーネルに対して最大 20 倍の事前処理速度向上を実現した。
重要な引用
IBM Research extends K-Search, the evolutionary kernel search framework from Berkeley Sky Lab, with a CUDA-to-MLX translation layer that transfers expert kernel knowledge to Apple Silicon
reaching 97% of FlashAttention performance and a ~20x faster Mamba SSM prefill
CUDA optimization knowledge can be translated into architecture-native MLX strategies rather than copied instruction-for-instruction
We developed a novel structured CUDA-to-MLX translation layer that lets K-Search take existing CUDA kernels as a knowledge base and adapt them into high-quality GPU kernels for Apple Silicon, rather than rebuilding from scratch.
編集コメントを表示
編集コメント
Apple Silicon の性能を最大限に引き出すための手法として、既存の CUDA エコシステムの知見を転用するアプローチは極めて実用的である。この技術は、マルチベンダー環境における AI デプロイメントの効率化に大きく寄与すると考えられる。
Source Article
元記事を日本語で読む
本文に関係しない購読案内、埋め込み通知、サイト内プロモーションは除いています。
図 1: CUDA から MLX への最適化変換マップ。CUDA の最適化ノウハウは、指令を一つずつコピーするのではなく、アーキテクチャに合わせたネイティブな MLX の戦略へと翻訳して活用できます。
私たちは計算の新たな時代を迎えています。ハードウェアは急速に変化しており、単に GPU が速くなるだけでなく、異なるベンダーから多様なチップが登場し、それぞれが独自のアーキテクチャを持ち、特定の AI ワークロード向けに設計されています。ソフトウェアも同様に進化を遂げており、AI によるコーディング支援ツールを使えば、数年前には数ヶ月かかった作業が今では数分で完了します。
計算の中心が AI に移った現在、GPU カーネルはその成功を支える重要な要素です。これは GPU の内部で動作する低レベルなプログラムであり、効率的に記述するのは容易ではありません。正しい実装には長年の専門知識が必要とされます。あるベンダーのハードウェアから別のベンダーへカーネルを移植するのはさらに難しく、多くの場合、最適化手法をゼロから再発見することになります。例えば CUDA エコシステムは、数十年にわたって蓄積された貴重なカーネルのノウハウを持っています。アテンションや状態空間モデルなど、重要な演算のための手動チューニング済みの実装が数千時間のエンジニアリングの成果として残されています。一方、Apple Silicon やカスタム AI アクセラレータなどの新しいハードウェアエコシステムは急速に成長していますが、こうした深い蓄積にはまだ至っていません。
本研究では、この専門知識を自動的に転送できるかどうかを検証しました。私たちは、カリフォルニア大学バークレー校のSky LabでCao氏らによって導入された進化型カーネル探索フレームワーク「K-Search」K-Search を基盤とし、Apple Silicon向けに設計された同社の機械学習フレームワークであるMLX用のバックエンドを追加して拡張しました。これにより、既存のCUDAカーネルを知識ベースとして活用し、ゼロから再構築するのではなく、高品質なApple Silicon用GPUカーネルへと適応させることができる、新しい構造化されたCUDA-to-MLX変換層を開発しました。
私たちのアプローチは、Apple Silicon上でネイティブのMLX Attentionカーネルと比較して0.97倍の高速化を達成し、Mamba SSMカーネルにおいてはコミュニティ製のmlx-lm実装に対して最大20倍のprefill速度向上を実現しました。これらの数値と、その性能向上のうち変換層が寄与した割合については、以下のセクションで詳述します。本稿ではApple Silicon向けのMLXカーネルに焦点を当てていますが、この手法はMLX固有のものではなく、CUDAの専門知識を転用できるあらゆるエコシステムに適用可能です。
なぜMLXなのか?
AppleのMLXフレームワークは2023年後半以降、目覚ましい普及を見せています。数百万台のMacBookやMac Studioに搭載されたApple Siliconにおいて、MLXはクラウドコストをかけずにローカルでAI推論を実行することを可能にします。ユニファイドメモリアーキテクチャを採用しているため、Mシリーズチップ上で7B〜70Bパラメータの中規模モデルにとって特に魅力的な選択肢となっています。
しかし、この勢いの裏には大きな課題が存在します。NVIDIA エコシステムでは当然視されているパフォーマンスに直結するカーネル——ページドアテンションや最適化された SSM スキャンカーネル、融合型 MoE ルーティングなど——が欠落しているか、ハードウェア固有のチューニングを施されていないために非効率な実装になっているケースが多いのです。MLX はモデルを正しく実行できますが、その性能を最大限に引き出せていないのが現状です。
この課題こそが、本稿で取り上げる K-Search の背景にあります。
K-Search とは何か?
K-Search は、カリフォルニア大学バークレー校の Sky Lab で初著者である Shiyi Cao 氏によって開発された、進化的なカーネル最適化フレームワークです。このシステムは、非効率な初期カーネルとハードウェア仕様が与えられると、反復的な最適化ループを開始します。まず LLM(大規模言語モデル)が次に試すべき最適化手法を推論し、コード生成モデルが候補となるカーネルを作成します。その後、これらの候補は実機上でコンパイルされ、ベンチマークされます。
測定結果は検索プロセスにフィードバックされ、システムは有望な方向性を追求しながら、効果のない経路を切り捨てていきます。そして性能が収束するまで、この精緻化のプロセスを繰り返します。
image**
アルゴリズム 1: 共進化型世界モデルによる K-Search。検索プロセスは、最も有望なアクションの選択とコードの実装・評価を繰り返して改善が頭打ちになるまで行うこと、そして挿入・更新・削除操作を通じて世界モデルを進化させることの両方を交互に行います。Cao et al. (2026) に基づき改変。
検索機能の基盤となるのは「仕様」です。これは、ハードウェアのルールや最適化パターン、数学的な制約を定義したドメイン固有の文書であり、生成されたコードが誤ったプリミティブを使用するハルシネーションを防ぎ、候補となるコードが実際にコンパイルされ、効率的に実行されることを保証します。
今回の実装では、単一のモデル(Gemini 3.5 Pro Preview)が両方の役割を担います。このモデルは推論状態の維持とカーネルの記述を同時に行います。推論パートでは「GPU カーネルのパフォーマンスエンジニア」としてプロンプトされ、提案を行う前に固定的な分析プロセスを踏むよう指示されます。具体的には、まずカーネルの種類(リダクション、スキャン、アテンション/ソフトマックスなど)を分類し、参照計算を標準形式に書き換えます。次にデータレイアウトとアクセスパターンを整理し、各ランタイム環境におけるボトルネックが帯域幅、レイテンシ、演算処理、あるいは同期のいずれにあるかを仮説立てます。その上で初めて、1 回のイテレーションで実装可能な単一の変更として候補となる最適化案を提示します。
私たちは、この永続的な推論状態を「ワールドモデル」と呼びます。これは単なる試行の羅列ではなく、決定(接頭辞)ツリーです。各ルートからリーフへのパスは完全な最適化プランを構成し、兄弟ノード間の枝分かれは競合する代替案を表します。
各ノードにはスコアが付けられます。全体評価は 0 から 10 の範囲、信頼度は 0 から 1 の範囲で、さらにメモリー帯域幅、レジスタ圧力、計算ハードウェア適合性への影響も個別に評価されます。これにより、検索アルゴリズムは部分的なプランを順位付けし、最も有望なものを拡張できます。
このツリーはラウンドを超えて維持・成長します。アイデアの洗練は親ノードを上書きするのではなく子ノードを追加する形で行われ、最良スコアが数回にわたって改善しない場合(停滞ウィンドウ)、検索は別の枝分かれへ探索を切り替えます。
以下は、アテンションカーネルの実行中に表示される単一ノードの例です。
リスト 1: K-Search のワールドモデルノードの例。 各候補最適化には、具体的なアクション、推定されたハードウェアへの影響、全体の優先度評価、そしてモデルの信頼度が記録されます。
図 2:K-Search の概要。このフレームワークは、探索木として構成された「検索状態(Search State)」$S_t$ を基盤に動作します。この木構造には、青で示される「クローズドノード(Closed nodes)」と、オレンジ色で示される「フロンティアのオープンノード(Frontier of Open nodes)」が含まれます。前者はプログラム $x_{12}$ のように既に訪問済みで処理済みの状態を、後者は $u_{13}$ のような未確定の仮説を表します。
このワークフローは 3 つのフェーズを経て進みます。まず「アクション選択」では、世界モデルが推定した優先度スコア V を基に、フロンティアから最も有望なアクションノードを取得します。次に「局所最適化」では、確率的ポリシー π_code が具体的な実装をサンプリングし、収束するまでこれを繰り返します。最後に「世界モデルの更新」では、LLM が軌跡を推論し、*Insert*(新しいノードを追加)を通じて探索ツリーを更新します。
操作(アクション)と、更新(V の調整。例えば u_11 が 0.9 から低下するなど)
0.6) と、*Prune*(有望度が低いノード $u_{10}$ などを削除する処理)です。
元の K-Search の論文では、この探索戦略を FlashInfer の CUDA カーネルに対して評価しました。GQA デコード、MLA デコード、MLA プレフィル、そして MoE にわたるテストで、K-Search は同じ 120 イテレーションの予算において、OpenEvolve や ShinkaEvolve よりも一貫して高い改善を示しました。これらの結果が、本稿で基盤とする探索フレームワークを確立するものです。残りの部分では、この最適化に関する知見が CUDA の枠を超えて転移可能かどうかを検証します。
図 3:K-Search のオリジナル論文からの主要な結果。3 回の試行を通じて、K-Search は FlashInfer の CUDA カーネル 4 つにおいて、OpenEvolve や ShinkaEvolve を上回る最良の探索スコア、ワークロードごとのカーネル性能、および速度向上の分布を実現しました。 Cao et al. (2026) から正確に再現。
MLX バックエンドの構築
K-Search を Apple Silicon 上で動かすため、私たちはまずネイティブの MLX バックエンドを構築しました。K-Search のために MLX に特化したタスクアダプターを実装し、以下を含んでいます:
- k_search/tasks/ に配置された MLX タスクバックエンド。MLX の Metal/C++ API を経由して、Apple Silicon 上でカーネルのコンパイルと実行を処理します。
- Metal/MLX カーネルの記述や修正のための、更新されたカーネル生成プロンプト。
- mlx.core の測定ユーティリティを活用した MLX に特化したベンチマーク統合。
CUDA の専門知識を MLX へ翻訳する
しかし、より興味深い課題は、単に K-Search を MLX で実行することではありません。鍵となる洞察は、熟練した CUDA カーネルには Apple GPU にも転用可能な数十年分の最適化ノウハウが詰まっているという点です。重要なのは、概念的なギャップを埋めることです。LLM に CUDA カーネルを与えて「移植して」と指示するだけでは不十分です。深いハードウェアの文脈がない場合、構文は正しいもののアーキテクチャ的に誤ったコード(不適切なタイルサイズ、無効なプリミティブ、メモリ仮定の不一致など)が生成されてしまいます。
私たちの翻訳レイヤーは以下の要素で構成されています:
概念マッピング表:CUDA プリミティブと MLX/Metal の対応関係を、厳格な制約条件付きで構造化した用語集です。例えば以下のようになります。
- __shared__ は Metal のスレッドグループメモリに相当しますが、容量制限は 32 KB と厳しく設定されています(NVIDIA では 48 KB)。
- warp_reduce は MMA(MMA: Matrix Multiply Accumulate)に変換されます(優先度が高い)。
- __syncthreads() は threadgroup_barrier(mem_flags::mem_tg) に置き換えられます。
H100 の HBM3 が提供する約 3.35 TB/s の帯域幅は、M3 Max のユニファイド DRAM で約 400 GB/s に相当します。この帯域幅の大きな差が、どの最適化手法に投資する価値があるかを根本から変えています。
MLX 固有のヒントとパターン:CUDA に直接相当しない演算のための具体的なコードレベルのパターン。例えば、8×8 の MMA タイルレイアウトにおける SIMD シャッフル XOR を用いたレジスタベースの行減算や、Apple の高速な exp2 ハードウェア命令を活用してソフトマックスを高速化する「exp2 技」($exp(x)$ を $exp_2(x \log_2 e)$ に置き換える手法)などです。
再利用可能なアサーション:進化的探索が維持すべき性質として、熟練したカーネルの振る舞いをコードそのものをコピーするのではなく再定義すること。
熟練したカーネルのパフォーマンスに追いつく:Attention カーネル
Apple Silicon 向けの MLX アテンションカーネルについて、3 つの構成で評価を行いました。(1) 単純なベースライン、(2) 追加の文脈情報なしでの純粋な進化探索、そして (3) 完全な文脈変換レイヤーです。この変換レイヤーは、FlashAttention-2 などの高性能カーネルから抽出したアーキテクチャ固有の実装知識をオプティマイザに提供し、進化探索が単純なカーネルから始めるのではなく、実装戦略について推論できるようにします。
図 4: アテンションカーネルのスタック化された最適化によるパフォーマンスのスケーリング。「Full Context(完全な文脈)」構成では、ダブルバッファリングやループアンローリングといった高度な戦略を独自に見つけ出し実装し、ほぼ専門家レベルのパフォーマンスを達成しています。
Apple の最先端アテンションカーネルに対して 0.26 倍から 0.97 倍へと速度が向上したことは、変換レイヤーの重要性を如実に示しています。完全な文脈を提供することで、進化させたカーネルは FlashAttention 2 の主要な最適化手法を独自に発見しました。具体的には、スレッドグループメモリのタイル処理、オンラインソフトマックス、メモリアクセスのための K-転置、そして exp2 トリックです。最後の exp2 トリックでは、すべてのソフトマックスの指数計算を底が 2 の指数関数に置き換えます。
\[e^x = 2^{x \log_2 e},\]
これは正確な計算であり、カーネルがランタイムでの基底変換コストを払うことなく、Apple の高速なハードウェア命令 fast::exp2() を直接利用できるようにします。
20 倍高速なプリフィル:Mamba SSM カーネル
K-Search がアテンションカーネルを超えて一般化できるか検証するため、私たちは Mamba で使用されている状態空間モデル(SSM)のカーネルにもこれを適用しました。アテンションとは異なり、計算上のボトルネックはソフトマックスではなく再帰的な状態更新にあるため、最適化の課題も大きく異なります。M1 Max 上で、進化した実装をコミュニティ版 MLX 実装(mlx-lm)と PyTorch の参照実装(mamba.py)と比較しました。
mamba-370m (f16) を M1 Max 64GB で評価した結果は以下の通りです:
| Metric | mlx-mamba (ours) | mlx-lm (community) | mamba.py |
|---|---|---|---|
| Decode | 152 tok/s | 116 tok/s | 40 tok/s |
| Prefill L=512 | 5,751 tok/s | 329 tok/s | 1,089 tok/s |
| Prefill L=1024 | 6,010 tok/s | 327 tok/s | 1,127 tok/s |
| Prefill L=2048 | 6,612 tok/s | 326 tok/s | 1,092 tok/s |
| Prefill L=4096 | 6,743 tok/s | 339 tok/s | 1,042 tok/s |
Table 1: mamba-370m (f16, M1 Max 64GB) におけるプリフィルとデコードのスループット。mlx-mamba(ours)は、コミュニティ版の mlx-lm ベースラインと比較して約 20 倍高いプリフィルスループットを達成しており、デコード性能も同等水準です。
mlx-lm と比較して約 20 倍の高速化を実現した理由は、たった一つの違いにあります。それは、mlx-lm が SSM のための並列スキャンを実装していない点です。状態の再帰更新は
h_t = \bar{a}_t h_{t-1} + \bar{b}_t という計算は、一見すると逐次的な処理に見えますが、各ステップを結合演算子 (\circ) を用いたペア (\bar{a}_t, \bar{b}_t) として表現できます。
(a_2, b_2) \circ (a_1, b_1) = (a_2 a_1, a_2 b_1 + b_2)
この演算は結合律を満たすため、再帰計算を完全に再現しつつ、O(N) の逐次処理ではなく O(log N) 段階の並列スキャン(プレフィックス・スキャン)で評価することが可能になります。
mlx-lm はこの最適化を省略し、トークンを一つずつ順に処理するため、Apple Silicon の計算リソースの大部分が遊んでしまいます。一方、我々が改良した Metal カーネルはこのスキャン演算を適用し、GPU のスループットを最大限に活用します。
この性能差は、プレフィル(事前生成)段階で顕著に現れます。ここでは全シーケンスが利用可能であるため、並列スキャンが可能になるからです。一方、デコード(単一トークン生成)段階では、1 ステップごとに新しいトークンが 1 つ追加されるだけで、並列化できるスキャンの余地がありません。そのため、デコード行はほぼ平坦な性能を示すのに対し、プレフィルでは約 20 倍の速度向上が見られます。
mamba.py は、PyTorch の参照実装に依存しているため、プレフィル・デコードの両方で低速です。
原文を表示
**
Figure 1: CUDA-to-MLX optimization translation map.** CUDA optimization knowledge can be translated into architecture-native MLX strategies rather than copied instruction-for-instruction.
We face a new epoch in computing. Hardware is changing rapidly — not just faster GPUs, but a growing range of chips from different vendors, each with its own architecture and often tailored to specific AI workloads. Software is changing just as fast, and AI coding tools now generate in minutes what took months of effort a few years ago.
With so much of computing now centered on AI, GPU kernels are a crucial component of its success. These are the low-level programs that run inside the GPU, and writing efficient ones is far from obvious — it takes years of expertise to get right. Transferring a kernel from one vendor’s hardware to another is harder still, and often means rediscovering the same optimizations from scratch. The CUDA ecosystem, for example, has accumulated decades of hard-won kernel expertise: hand-tuned implementations of attention, state space models, and other critical operations representing thousands of engineering hours. Newer hardware ecosystems (Apple Silicon, custom AI accelerators, and others) are growing fast but lack this depth.
In this work we ask whether that expertise can be transferred automatically. We built on K-Search, an evolutionary kernel search framework introduced by Cao et al. at Berkeley Sky Lab that uses AI to optimize GPU kernels, and extended it with a backend for MLX — Apple’s machine-learning framework for its own Apple Silicon chips. We developed a novel structured CUDA-to-MLX translation layer that lets K-Search take existing CUDA kernels as a knowledge base and adapt them into high-quality GPU kernels for Apple Silicon, rather than rebuilding from scratch.
We show that our approach reaches near-expert level performance on Apple Silicon with 0.97x speedup compared to the native MLX Attention kernel, and up to a 20x prefill speedup over the community mlx-lm implementation on the Mamba SSM kernel; we report the numbers, and how much of the gain comes from the translation layer, in the sections below. Although we focus on MLX kernels for Apple Silicon, the method is not specific to MLX and applies to any ecosystem where CUDA expertise is transferable.
Why MLX?
Apple’s MLX framework has seen remarkable adoption since late 2023. With Apple Silicon in hundreds of millions of MacBooks and Mac Studios, MLX enables local AI inference without cloud costs. The unified memory architecture makes it especially attractive for mid-sized models (7B–70B parameters on M series chips).
Yet beneath this momentum lies a significant gap: many performance-critical kernels that the NVIDIA ecosystem takes for granted: paged attention, optimized SSM scan kernels, fused MoE routing are either absent or naive without hardware-specific tuning. MLX runs models correctly but often leaves significant performance on the table.
This gap is what motivates the rest of this post.
What is K-Search?
K-Search is an evolutionary kernel optimization framework originally developed by our first author Shiyi Cao at UC Berkeley Sky Lab. Given a naive kernel and a hardware specification, it runs an iterative optimization loop: an LLM reasons about which optimizations to try next, a code-writing model generates candidate kernels, and those candidates are compiled and benchmarked on real hardware.
Measurements feed back into the search, which keeps refining, pursuing promising directions and dropping dead ends until performance converges.
**
Algorithm 1: K-Search via co-evolving world models.** The search alternates between selecting the most promising action, instantiating and evaluating code until improvement stagnates, and evolving the world model through insert, update, and prune operations. Adapted from Cao et al. (2026).
Search is grounded by a Spec: a domain-specific document encoding hardware rules, optimization patterns, and mathematical constraints which keeps generated code from hallucinating invalid primitives and ensures candidates will actually compile and run efficiently.
In our runs, a single model (Gemini 3.5 Pro Preview) plays both roles: it maintains the reasoning state and writes the kernels. The reasoning half is prompted as a “GPU kernel performance engineer” and asked to work through a fixed analysis before proposing anything: classify the kernel (reduction, scan, attention/softmax, …), rewrite the reference computation in canonical form, map out data layout and access patterns, and hypothesize the likely bottleneck (bandwidth, latency, compute, or synchronization) in each runtime regime. Only then does it emit candidate optimizations, each as a single change implementable in one iteration.
We call the persistent reasoning state a *world model*. Rather than a flat list of things to try, it is a decision (prefix) tree: each root→leaf path composes a full optimization plan, and sibling branches are competing alternatives. Every node is scored — an overall_rating in [0, 10], a confidence in [0, 1], and per-node impacts on memory bandwidth, register pressure, and compute/hardware fit — so the search can rank partial plans and expand the most promising ones. The tree persists and grows across rounds: refining an idea adds a child node rather than overwriting its parent, and if the best score fails to improve for a few rounds (a stagnation window) the search backs off to explore an alternative branch. A single node, as it appears mid-run on the attention kernel, looks like this:
{
"action": "Replace the threadgroup-memory softmax reduction
with a register-only reduction: each SIMD group
owns 8 query rows and reduces across lanes with
simd_shuffle_xor, removing a threadgroup_barrier.",
"difficulty_1_to_5": 4,
"impacts": {
"memory_bandwidth": 8,
"register_pressure": 4, // risk: spill if Br > 8
"compute_hw_fit": 9 // SIMD width 32; keep tile 8x8
},
"overall_rating_0_to_10": 8,
"confidence_0_to_1": 0.7
}
Listing 1: Example K-Search world-model node. Each candidate optimization records a concrete action, estimated hardware impacts, an overall priority rating, and the model's confidence.
**
Figure 2: Overview of K-Search. The framework operates on a Search State $S_t$ structured as a search tree. The tree consists of Closed nodes (blue, visited states with attached program like $x_{12}$) and a Frontier of Open nodes (orange, pending hypotheses like $u_{13}$). The workflow iterates through three phases: (1) Action Selection, where the most promising action node is retrieved from the frontier based on world model estimated priority score $V$; (2) Local Refinement, where a stochastic policy $\pi_{\mathrm{code}}$ samples concrete implementations until stagnation; and (3) World Model Update**, where the LLM reasons over the trajectory to update the search tree via *Insert* (adding new actions), *Update* (adjusting $V$, e.g., $u_{11}$ dropping from 0.9 to 0.6), and *Prune* (removing less promising nodes like $u_{10}$).
The original K-Search paper evaluated this search strategy on CUDA kernels from FlashInfer. Across GQA decode, MLA decode, MLA prefill, and MoE, K-Search improved more consistently than OpenEvolve and ShinkaEvolve over the same 120-iteration budget. These results establish the search framework we build on here; the remainder of this post asks whether its optimization knowledge can transfer beyond CUDA.
**
Figure 3: Main results from the original K-Search paper.** Across three runs, K-Search achieves stronger best-so-far search scores, per-workload kernel performance, and speedup distributions than OpenEvolve and ShinkaEvolve on four FlashInfer CUDA kernels. Reproduced exactly from Cao et al. (2026).
Building an MLX backend
To bring K-Search to Apple Silicon, we first built a native MLX backend. We implemented a full MLX-specific task adapter for K-Search, including:
- An MLX task backend in k_search/tasks/ handling kernel compilation and execution on Apple Silicon via MLX’s Metal/C++ APIs.
- Updated kernel generator prompts for writing and modifying Metal/MLX kernels.
- MLX-specific benchmarking integration using mlx.core measurement utilities.
Translating CUDA expertise to MLX
However, the more interesting challenge was not simply running K-Search on MLX. The key insight is that expert CUDA kernels encode decades of optimization knowledge that is transferable to Apple GPU if you can bridge the conceptual gap. Simply handing an LLM a CUDA kernel and asking it to port it is not enough: without deep hardware context, it produces code that is syntactically valid but architecturally wrong (wrong tile sizes, invalid primitives, mismatched memory assumptions).
Our translation layer consists of:
- Concept mapping tables: A structured glossary of CUDA primitives and their MLX/Metal equivalents with hard constraints. For example:
__shared__ maps to Metal threadgroup memory but with a hard 32 KB limit (vs. NVIDIA’s 48 KB)
- warp_reduce maps to MMA (preferred)
- __syncthreads() becomes threadgroup_barrier(mem_flags::mem_tg)
- H100’s ~3.35 TB/s HBM3 maps to M3 Max’s ~400 GB/s unified DRAM a bandwidth difference that reshapes which optimizations are worth pursuing.
- MLX-specific hints and patterns: Concrete code-level patterns for operations with no direct CUDA equivalent, such as register-based row reductions using simd_shuffle_xor in an 8×8 MMA tile layout, or the “exp2 trick” (replacing $exp(x)$ with $exp_2(x \log_2 e)$) for faster softmax on Apple’s fast $exp_2$ hardware instruction.
- Reusable assertions: Expert kernel behaviors reframed as properties the evolutionary search must preserve, rather than code to copy.
Matching expert kernel performance: the Attention kernel
We evaluate three configurations of an MLX attention kernel for Apple Silicon: (1) a naive baseline, (2) pure evolution with no additional provided context, and (3) a full context translation layer, which supplies the optimizer with architecture-specific implementation knowledge extracted from high-performance kernels (e.g., FlashAttention-2), letting the evolutionary search reason about implementation strategies rather than starting from a naive kernel. Together, these three configurations let us isolate the exact impact of the translation layer.
**
Figure 4:** Performance scaling of the Attention Kernel through stacked optimizations. The "Full Context" configuration successfully discovers and implements advanced strategies like double buffering and loop unrolling, achieving near-expert performance.
The jump from 0.26× to 0.97× the speed of Apple’s state-of-the-art attention kernel — illustrates how much the translation layer matters. With full context, the evolved kernel independently discovers the key optimizations in FlashAttention 2: threadgroup memory tiling, online softmax, K-transposition for memory access, and the exp2 trick. The last of these replaces every softmax exponential with a base-2 exponential,
\[e^x = 2^{x \log_2 e},\]
which is exact and lets the kernel use Apple’s fast fast::exp2() hardware instruction directly instead of paying for a base conversion at runtime.
A 20× faster prefill: the Mamba SSM kernel
To evaluate whether K-Search generalizes beyond attention kernels, we applied it to the state-space model (SSM) kernel used by Mamba. Unlike attention, the computational bottleneck is a recurrent state update rather than a softmax, providing a substantially different optimization challenge. We compare the evolved implementation against the community MLX implementation (mlx-lm) and the PyTorch reference implementation (mamba.py) on an M1 Max.
Evaluated on mamba-370m f16, M1 Max 64GB:
Metric
mlx-mamba (ours)
mlx-lm (community)
mamba.py
Decode
152 tok/s
116 tok/s
40 tok/s
Prefill L=512
5,751 tok/s
329 tok/s
1,089 tok/s
Prefill L=1024
6,010 tok/s
327 tok/s
1,127 tok/s
Prefill L=2048
6,612 tok/s
326 tok/s
1,092 tok/s
Prefill L=4096
6,743 tok/s
339 tok/s
1,042 tok/s
Table 1: Prefill and decode throughput on mamba-370m (f16, M1 Max 64GB). mlx-mamba (ours) reaches ~20× higher prefill throughput than the community mlx-lm baseline, while decode remains comparable.
The ~20× prefill speedup over mlx-lm comes down to one difference: mlx-lm does not implement a parallel scan for the SSM. The state recurrence
\[h_t = \bar{a}_t h_{t-1} + \bar{b}_t\]
looks inherently sequential, but each step can be written as a pair $(\bar{a}_t, \bar{b}_t)$ under the associative combine
\[(a_2, b_2) \circ (a_1, b_1) = \left(a_2 a_1,\ a_2 b_1 + b_2\right),\]
which reproduces the recurrence exactly. Because the operator is associative, the whole sequence can be evaluated with a parallel (prefix) scan in $O(\log N)$ dependent steps instead of $O(N)$. mlx-lm skips this and processes tokens one at a time, leaving most of Apple Silicon’s compute idle; our evolved Metal kernel applies the scan and makes much fuller use of GPU throughput. The gain shows up in prefill, where the full sequence is available to scan in parallel, and not in single-token decode, where there is only one new token per step and no scan to parallelize — which is why the decode row is roughly flat while prefill is ~20×.
mamba.py is slow on both prefill and decode because it is a PyTorch reference implemen
AI算出
技術分析ainew評価高い
Berkeley AI Research が公開した K-Search は、特定のハードウェアアーキテクチャ間でのカーネル最適化ノウハウを転送する画期的な技術的アプローチであり、具体的なベンチマーク数値と実装戦略が含まれているため、技術分析として分類します。
6つの評価軸を見る
- AI関連度
- 100
- 情報源の信頼性
- 25
- 新規性
- 75
- 調べる価値
- 75
- 重複の少なさ
- 100
- 日本での有用性
- 50
関連記事
今日のまとめ
AIデイリーブリーフで今日の重要ニュースをまとめ読み