Communitygithub.com

G1Joshi/Agent-Skills

JAX에 대한 전문적인 도움을 제공합니다. Autograd, XLA 컴파일(`jit`), 벡터화(`vmap`), 병렬화(`pmap`)를 다루며, 고성능 수치 연산 및 최첨단 딥러닝 연구에 사용됩니다.

Agent-Skills란 무엇인가요?

이 스킬은 JAX 라이브러리를 활용한 고성능 수치 연산 및 딥러닝 연구를 지원합니다. JAX는 Autograd(자동 미분)와 XLA(컴파일)를 결합하여 GPU/TPU에서 가속화된 선형 대수 연산을 제공하며, 2025년 기준 Flax NNX(PyTorch 스타일 OOP)가 표준으로 자리 잡았습니다. `jit`(컴파일), `grad`(미분), `vmap`(벡터화) 같은 함수 변환을 자연스럽게 연결하여 사용자 정의 딥러닝 모델을 구축할 수 있고, `pmap`이나 샤드 맵을 이용해 다중 디바이스 분산 훈련도 가능합니다. 주요 패턴으로는 순수 함수형 코드 작성, 명시적 PRNG 키 관리, 상태 유지 모델(Equinox 등) 사용 사례를 다루며, `ConcretizationTypeError`나 `PRNGKey` 재사용 같은 일반적인 문제에 대한 트러블슈팅 가이드도 포함되어 있습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/G1Joshi/Agent-Skills/tree/HEAD/skills/ai-ml/jax

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

JAX

JAX는 "강화된 NumPy"입니다. Autograd(자동 미분)와 XLA(컴파일)를 결합합니다. 2025년에는 Flax NNX(PyTorch 스타일의 OOP)가 표준이 되고 있습니다.

사용 시기

  • 고성능 수치 및 과학 컴퓨팅: GPU/TPU에서 가속화된 선형 대수를 위한 Autograd 및 XLA 컴파일.
  • 커스텀 딥러닝 연구: 프레임워크 복잡성 없이 Flax, Haiku 또는 Equinox로 신경망 구축.
  • 구성 가능한 함수 변환: jit(컴파일), grad(도함수), vmap(벡터화)의 원활한 연결.
  • 다중 디바이스 분산 훈련: pmap 및 샤드 맵(jax.experimental.shard_map)을 사용하여 클러스터 전체에서 계산 병렬화.

빠른 시작

import jax
import jax.numpy as jnp

# JIT-컴파일된 행렬 곱셈 및 자동 미분
@jax.jit
def loss_fn(w, x, y):
    pred = jnp.dot(x, w)
    return jnp.mean((pred - y) ** 2)

# 값과 그래디언트를 동시에 계산
grad_fn = jax.grad(loss_fn)

w = jnp.array([1.0, 2.0])
x = jnp.array([[1.0, 0.5], [2.0, 1.0]])
y = jnp.array([2.0, 4.0])

grads = grad_fn(w, x, y)
print("그래디언트:", grads)

핵심 개념

#구성 가능한 함수 변환: jit, grad 및 vmap

적시 컴파일, 자동 미분 및 자동 배치 처리의 결합:

import jax
import jax.numpy as jnp

# 순수 함수 정의
def loss_fn(w, x, y):
    pred = jnp.dot(x, w)
    return jnp.mean((pred - y) ** 2)

# 변환 1: 가중치에 대한 자동 그래디언트
grad_fn = jax.grad(loss_fn)

# 변환 2: XLA를 통한 JIT 컴파일로 극한의 GPU 속도 향상
fast_grad_fn = jax.jit(grad_fn)

# 변환 3: 배치 전체에 대한 자동 벡터화
# batch_loss_fn은 루프 없이 2D 행렬을 자동으로 처리
vmapped_loss = jax.vmap(loss_fn, in_axes=(None, 0, 0))

# 샘플 계산
key = jax.random.PRNGKey(42)
w = jax.random.normal(key, (3,))
x = jnp.array([[1.0, 2.0, 3.0]])
y = jnp.array([5.0])

grad_val = fast_grad_fn(w, x, y)
print("계산된 그래디언트:", grad_val)

#명시적 PRNG 키 관리

상태가 없는 의사 난수 생성:

import jax

# 루트 PRNG 키 초기화
key = jax.random.PRNGKey(2026)

# JAX 키는 명시적으로 분할되어야 하며 절대 재사용되지 않음
key, subkey1, subkey2 = jax.random.split(key, 3)

data_normal = jax.random.normal(subkey1, shape=(4, 4))
data_uniform = jax.random.uniform(subkey2, shape=(4, 4))

print("정규 샘플 평균:", jnp.mean(data_normal))

#Equinox와 순수 함수를 사용한 상태 유지 모델

순수 JAX 함수 위에 구축된 표현력 있는 객체 지향 신경망:

import equinox as eqx
import jax
import jax.numpy as jnp

class SimpleMLP(eqx.Module):
    linear1: eqx.nn.Linear
    linear2: eqx.nn.Linear

    def __init__(self, in_features, out_features, key):
        k1, k2 = jax.random.split(key)
        self.linear1 = eqx.nn.Linear(in_features, 64, key=k1)
        self.linear2 = eqx.nn.Linear(64, out_features, key=k2)

    def __call__(self, x):
        x = jax.nn.relu(self.linear1(x))
        return self.linear2(x)

key = jax.random.PRNGKey(0)
model = SimpleMLP(in_features=10, out_features=2, key=key)
sample_input = jnp.ones((10,))
output = model(sample_input)
print("모델 출력:", output)

일반적인 패턴

vmap을 사용한 배치 벡터화

문제: 배치에 대해 함수를 평가하기 위해 수동 Python 루프를 작성하면 실행 속도가 느려집니다.

해결책: jax.vmap을 사용하여 단일 예제 함수를 자동으로 벡터화합니다:

def predict_single(w, x):
    return jnp.dot(x, w)

# 배치 차원(x의 축 0)에 대해 자동 벡터화
predict_batch = jax.vmap(predict_single, in_axes=(None, 0))

batch_x = jnp.ones((100, 10))
weights = jnp.ones(10)
predictions = predict_batch(weights, batch_x) # 출력 형태: (100,)

모범 사례 (2026)

  • 권장: 순수 함수형 코드를 작성합니다: 부작용 없음, 내부 배열 변경 없음(x[idx] = val 대신 x.at[idx].set(val) 사용).
  • 권장: 성능이 중요한 함수를 @jax.jit으로 래핑하여 XLA 컴파일을 트리거합니다.
  • 권장: 난수가 생성될 때마다 PRNG 키를 명시적으로 분할합니다(jax.random.split(key)).
  • 권장: 원시 매개변수 사전을 작성하는 대신 Equinox나 Flax Linen과 같은 현대적인 고수준 라이브러리를 사용합니다.
  • 비권장: JIT 함수 내 동적 트레이서에서 표준 Python 조건문(if x > 0:)을 사용하지 않습니다. jax.lax.cond를 사용하세요.
  • 비권장: PRNG 키를 재사용하지 않습니다. 키를 재사용하면 통계적으로 상관된 난수가 생성됩니다.
  • 비권장: jit, grad 또는 vmap으로 변환된 함수 내에서 전역 변수를 변경하지 않습니다.

문제 해결

오류원인해결책
ConcretizationTypeError: Abstract tracer value used in Python if/whilePython 조건부 분기가 jit 내부의 동적 JAX 배열 값에 의존합니다.표준 Python if 대신 jax.lax.cond 또는 jax.lax.while_loop를 사용하세요.
JAX arrays are immutable내부 할당 시도(arr[0] = 5).함수형 업데이트 구문 사용: arr = arr.at[0].set(5).
PRNGKey reuse warning / identical randomness동일한 PRNG 키를 재사용하면 동일한 난수가 생성됩니다.각 난수 연산 전에 키를 분할하세요: key, subkey = jax.random.split(key).

참고 자료

Individual skills in this repo

This repo contains 11 individual skills — each has its own dedicated page.

G1Joshi/Agent-Skills

Expert Dask distributed computing assistance covering Dask DataFrames, Arrays, Futures, and cluster scaling. Use when analyzing datasets too large for pandas on a single machine or multi-node cluster.

G1Joshi/Agent-Skills

Expert dbt (data build tool) assistance covering SQL modeling, Jinja macros, tests, documentation, and semantic layer. Use when building analytics engineering pipelines on BigQuery, Snowflake, or PostgreSQL.

G1Joshi/Agent-Skills

Expert Ray distributed computing assistance covering Ray Core (actors, tasks), Ray Train, Ray Tune, and Ray Serve. Use when scaling Python compute and ML training across multi-node clusters.

G1Joshi/Agent-Skills

Expert Git version control assistance covering branching, interactive rebase, cherry-pick, submodules, worktrees, and conflict resolution. Use when managing source code history and collaboration workflows.

G1Joshi/Agent-Skills

Expert K9s CLI assistance covering terminal Kubernetes cluster navigation, real-time log streaming, port forwarding, and pod debugging. Use when managing and troubleshooting Kubernetes clusters with speed.

G1Joshi/Agent-Skills

Expert SWC assistance covering high-performance Rust-based JavaScript/TypeScript compilation, .swcrc configuration, Jest testing via @swc/jest, and minification. Use when replacing Babel with SWC for faster builds, accelerating test execution, or compiling modern ECMAScript features.

G1Joshi/Agent-Skills

Expert Tig assistance covering text-mode interface for Git, interactive staging, commit graph visualization, diff exploration, and blame navigation. Use when navigating Git commit history in the terminal, staging hunks interactively, browsing file changes, or reviewing revisions.

G1Joshi/Agent-Skills

Expert Vim assistance covering modal editing, .vimrc configuration, registers, macros, search/replace, and plugin management via vim-plug. Use when editing text efficiently in terminal environments, writing Vimscript, recording macros, or configuring core Vim settings.

G1Joshi/Agent-Skills

Expert Zed editor assistance covering high-performance Rust-based text editing, multi-buffer editing, language server protocols (LSP), and AI assistant integrations. Use when configuring Zed settings.json, setting up language extensions, collaborating in real-time channels, or optimizing editor startup speed.

G1Joshi/Agent-Skills

Expert Zsh assistance covering shell customization, Oh My Zsh plugins, Zinit plugin manager, prompt engineering (Starship/Powerlevel10k), and shell scripting. Use when configuring .zshrc, writing Zsh automation scripts, optimizing shell startup time, or configuring tab-completion.

G1Joshi/Agent-Skills

Expert [skill-name] assistance covering [feature 1], [feature 2], and [feature 3]. Use when [working with X], [debugging Y], or [implementing Z].

관련 스킬