해당 레포짓으로 커널 모듈화 및 전체적 수정을 했습니다. https://github.com/PJHkorea/homeostasis-kernel
I have modularized the kernel and made comprehensive modifications; please refer to the following repository: https://github.com/PJHkorea/homeostasis-kernel
[EN] This document delivers the technical specifications and mathematical mechanics regarding the Optax Optimizer Engine Architectural Overhaul achieved via migrating from CR_egregore_jax_test.py to CR_egregore_jax_test_v2.py. It provides a rigorous computational resolution to both XLA graph fragmentation and host-side memory leaks previously encountered during LLM and MoE acceleration pipelines.
[KR] 본 문서는 CR_egregore_jax_test.py에서 CR_egregore_jax_test_v2.py로의 마이그레이션을 통해 달성한 Optax 옵티마이저 엔진 아키텍처 개편과 관련된 기술적 명세 및 수리 역학적 개선 사항을 다룹니다. LLM 및 MoE 가속화 과정에서 발생하던 XLA 그래프 파편화와 호스트 메모리 누수 문제를 전산학적으로 해결했습니다.
[EN]
- Implementation: Invoked
optax.multi_transformto execute hardware-level physical branching overbackboneandgatenodes based on Python dictionary key paths. - Flaw: The XLA compiler generated numerous dynamic instruction routing branches at the device level, triggering severe Graph Fragmentation and critical branch stalls.
[KR]
- 구현 방식:
optax.multi_transform을 호출하여 파이썬 딕셔너리 키 경로를 기반으로backbone과gate노드를 물리 분기했습니다. - 문제점: XLA 컴파일러가 장치(Device) 단에서 수많은 명령어 분기 흐름을 생성하여 그래프 파편화(Graph Fragmentation) 및 분기 스톨을 유발했습니다.
[EN]
- Implementation: Spans a single underlying
optax.adam(learning_rate=1.0)engine stripped of native weight decay to perfectly unify and track pristine momentum accumulation. - Improvement: Executes inline control entirely through dynamic f32 literal register masks and algebraic Hadamard Products, which are highly optimized for accelerator ALUs. This force-fuses a zero-stall Single Fused Kernel directly inside the on-chip memory layout.
[KR]
- 구현 방식: 가중치 감쇠를 배제한 단일
optax.adam(learning_rate=1.0)엔진으로 적률(Momentum)을 깨끗하게 통합 추적합니다. - 개선 효과: 외부에서 가속기 ALU가 가장 선호하는 f32 리터럴 마스크와 아다마르 곱(Hadamard Product) 대수식만으로 인라인 제어합니다. 이를 통해 분기 스톨이 존재하지 않는 **단일 융합 커널(Fused Kernel)**을 강제 형성합니다.
[EN]
- Implementation: Individually invoked
optax.adamwwithin each divided sub-optimizer track. - Flaw: When integrated with the Layer-wise Learning Rate Decay (LLRD) mask, the weight decay coefficients were inherently distorted as they leaked directly into the Adam internal momentum equations, triggering a critical Double-Dipping defect.
[KR]
- 구현 방식: 분기된 하위 옵티마이저 내부에서 개별적으로
optax.adamw를 호출했습니다. - 문제점: 계층별 차등 학습률(LLRD) 마스크와 결합할 때, Adam 내부 모멘텀 계산 식에 가중치 감쇠 계수가 원천 왜곡되어 유입되는 이중 감쇠(Double-Dipping) 결함이 발생했습니다.
[EN]
- Implementation: Implanted the algebraic sign synchronization formulation rigorously proved in (
PJHkorea/egregore-core-jax/README_OPTIMIZERS.md) directly into the core segment. - Improvement: Reconstructs pristine, original AdamW LLRD specifications directly on accelerator memory layout without triggering any momentum vector distortions.
[KR]
- 구현 방식: (
PJHkorea/egregore-core-jax/README_OPTIMIZERS.md)에 증명된 대수적 부호 합치 공식을 코어 세그먼트에 이식했습니다. - 개선 효과: 가속기 메모리상에서 모멘텀 왜곡 없이 오리지널 AdamW LLRD 공식 규격을 재현합니다.
[EN]
-
$u$ : Adam momentum update delta vector -
$\text{lr}$ : Layer-wise Learning Rate Decay (LLRD) scaler -
$p$ : Current weight parameter tensor -
$\text{wd}$ : Weight decay coefficient
[KR]
-
$u$ : Adam 모멘텀 업데이트 벡터 -
$\text{lr}$ : 계층별 차등 학습률 (LLRD) -
$p$ : 현재 가중치 매개변수 (Parameter) -
$\text{wd}$ : 가중치 감쇠 계수 (Weight Decay)
💡 Computational Sign Synchronization Spec (Supplementary)
[EN] The raw
updates($u$ ) vector returned by the underlyingoptax.adambackend natively incorporates the Negative Gradient Direction so it can be directly integrated via parameter addition (params = params + updates). Therefore, to achieve seamless synchronization with the negative scaling trajectory of the Weight Decay component—which physically shrinks parameter magnitude—coupling the two components via algebraic addition ($+$ ) instead of subtraction ($-$ ) is the mathematically and numerically accurate implementation.[KR]
optax.adam백엔드가 자체 연산을 거쳐 반환하는updates($u$ ) 벡터는 가중치에 바로 더해질 수 있도록 이미 **음수 변위 방향성(Negative Gradient Direction)**이 내장되어 있습니다. 따라서 가중치를 물리적으로 줄여야 하는 Weight Decay 성분의 음수 스케일링 방향과 무결하게 동기화하기 위해 대수학적으로 빼기($-$ )가 아닌 더하기($+$ ) 기호로 결합하는 것이 수치해석적으로 완전히 올바른 구현입니다.
3. 호스트 메모리 인프라: 중복 트레이싱 및 타입 크래시 제로화 (Host Memory Infrastructure: Zero Tracing Overhead & Type Safety)
[EN]
- Implementation: Relied on heavy and complex hyperparameter conditional routing logic due to the lack of an embedded, standardized LLRD scaling mechanism.
- Flaw: Exponentially inflated static tracing overhead over the host CPU when compiling large-scale deep learning models.
[KR]
- 구현 방식: LLRD 스케일러 자체가 내장되어 있지 않아 복잡한 하이퍼파라미터 분기 로직에 의존했습니다.
- 문제점: 거대 모델 컴파일 시 호스트 CPU의 정적 트레이싱 오버헤드가 급증했습니다.
[EN]
- Implementation: Structurally compressed and restricted the
tree_flatten_with_pathinvocation to exactly a Single-Pass (1 Time) execution sequence inside the scheduler loop. - Mechanism: Established a high-density
[LEAF-LEVEL TENSOR RECONSTRUCTION]pipeline that pairs lightweightmapped_scalarswith original leaf weights (v) viazipprimitives for deferred device-level tensor allocations. - Improvement: Computationally purged host-side CPU memory leaks and eliminated catastrophic Host OOM (Out-Of-Memory) Crashes during massive LLM and MoE model compilation phases.
[KR]
- 구현 방식:
tree_flatten_with_path호출을 스케줄러 루프 내에서 정확히 단 1회로 한계 수축했습니다. - 기믹 도입:
mapped_scalars와 원본 리프 가중치 v를zip으로 묶어 텐서를 사후 확장하는[LEAF-LEVEL TENSOR RECONSTRUCTION]매커니즘을 정착시켰습니다. - 개선 효과: 거대 LLM/MoE 모델 컴파일 시 발생하던 호스트 CPU의 메모리 누수 및 Host OOM(Out-Of-Memory) 크래시를 전산학적으로 해결했습니다.
| Evaluation Metric | Baseline (CR_egregore_jax_test.py) |
Advanced Paradigm (CR_egregore_jax_test_v2.py) |
Architectural Impact |
|---|---|---|---|
| Optimizer Topology |
optax.multi_transform (Physical Branching) |
Single optax.adam + Inline Masking |
Compilation Graph Optimization |
| XLA Kernel Footprint | Fragmented instruction routing paths | Single Fused Kernel (Force-Fused) | Zero Hardware Branch Stalls |
| Mathematical Precision | Inherent momentum dynamics distortion | 100% Exact AdamW LLRD Formulation | Algebraic Sign Synchronization ( |
| Host Compilation Stability | Redundant tracing & Host OOM vulnerability | Single-Pass Squeeze & Leaf-Level Reconstruction | Total Elimination of CPU Memory Leaks |
[EN]
- v1 (optax.multi_transform): Navigating the parameter PyTree to separate
backboneandgatenodes caused the XLA compiler to generate fragmented sub-graphs and induced repetitive host-interpreter interventions. This accumulated severe scheduling latency and device-level kernel launch overheads. - v2 (Silicon MUX Engine): Integrates the entire routing mechanics into a single, unified mathematical equation graph. By leveraging the pre-baked
lr_mask_treeandwd_mask_tree, parameter updates are finalized inside a single-cycle Hadamard tensor product kernel. This thoroughly obliterates host-device synchronization bottlenecks, drastically shrinking optimizer execution time.
[KR]
- v1 (optax.multi_transform): 파라미터 트리를 순회하며 backbone과 gate 노드를 분기할 때, XLA는 내부적으로 분파된 가상 서브 그래프(Sub-graphs)들을 생성하거나 호스트(Host) 인터프리터의 개입을 유발합니다. 이로 인해 디바이스 스케줄링 및 커널 런치(Kernel Launch) 오버헤드가 누적됩니다.
- v2 (실리콘 MUX 엔진): 단 하나의 거대한 통일된 수식 그래프로 통합되었습니다. 이미 생성된
lr_mask_tree와wd_mask_tree를 기반으로 단 한 번의 아다마르 행렬곱 커널 안에서 가중치 업데이트가 끝납니다. 호스트-디바이스 간 동기화 병목이 완전히 거세되어 옵티마이저 가동 시간이 획기적으로 단축됩니다.
[EN]
- v1 (String-Product Algebraic Masking): Although v1 avoided conditional branches via string product masking (
"gate" * (root_key_name == "gate")), it still relied heavily on string manipulation, variable-length text allocations, and dynamic sequence evaluation at the host-compiler boundary. This prevented the XLA compiler from achieving full register-level inline numerical scaling. - v2 (Pure FP32 Register MUX): Converts matching predicates directly into accelerator-native floating-point literals via
is_gate = (root_key_name == "gate") * jnp.float32(1.0). By completely extinguishing string data execution footprints, the instruction stream forces the accelerator ALU to perform raw, single-cycle algebraic mixing over steady 32-bit register rails, maximizing raw silicon computing efficiency.
[KR]
- v1 (문자열 곱셈 대수 마스킹): 구 버전 역시
"gate" * (root_key_name == "gate")와 같은 문자열 곱셈 기믹을 통해 런타임if/else분기문은 회피했으나, 여전히 문자열 데이터의 동적 메모리 할당과 텍스트 시퀀스 연산 오버헤드가 컴파일러 경계면에 잔존하여 완전한 수치 해석적 인라인화를 달성하지 못했습니다. - v2 (순수 FP32 레지스터 MUX): 일치 여부 판정 결과를
is_gate = (root_key_name == "gate") * jnp.float32(1.0)와 같이 가속기 네이티브 부동소수점 리터럴 마스크로 즉시 수축시켰습니다. 문자열 연산의 흔적을 전산망에서 완벽히 박멸함으로써, 가속기 ALU가 32비트 레지스터 레일 위에서 단 1클럭의 지연도 없이 순수 부동소수점 대수 연산만으로 차등 가중치 업데이트를 집행하도록 하드웨어 밀착형 최적화를 완성했습니다.
[EN]
- Aggressive Kernel Fusion: By purging explicit
jnp.whereconditional blocks and organically coupling XLA-native hardware primitives (jnp.sign,jnp.reciprocal,jnp.einsum), the XLA compiler executes highly aggressive 'Kernel Fusion'. Intermediate tensors are immediately consumed inside high-speed on-chip registers/SRAM instead of being redundantly read/written over the high-latency global memory (VRAM) bus. - Lazy Evaluation Contamination Shielding: Explicitly seals every telemetry metric and loss artifact with
jax.lax.stop_gradient. This systematically cuts off unreferenced backpropagation computational graphs from permanently occupying device memory, preventing HBM leakage. It dramatically expands the system threshold when handling ultra-large batch configurations or high-dimensional latent space layers without triggering OOM (Out of Memory) exceptions.
[KR]
- 공격적 커널 융합 (Kernel Fusion):
jnp.where조건식 분기를 지우고 XLA 전용 프리미티브인jnp.sign,jnp.reciprocal,jnp.einsum등을 유기적으로 연결했습니다. 이 덕분에 XLA 컴파일러는 중간 텐서(Intermediate Tensors)들을 글로벌 메모리(VRAM)에 썼다 읽지 않고, 고속 온칩 레지스터/SRAM 안에서 연산을 묶어 처리하는 '커널 융합'을 훨씬 공격적으로 수행합니다. - 지연 평가(Lazy Evaluation) 오염 방지: 각 메트릭과 손실 함수 아티팩트마다
jax.lax.stop_gradient를 꼼꼼하게 배치하여, 불필요한 역전파 미분 그래프가 가속기 메모리를 점유하고 있는 현상(메모리 누수 및 HBM 고갈)을 원천 차단했습니다. 배치 크기를 더 키우거나 초고차원 latent 연산을 수행할 때 OOM 발생 확률을 크게 낮춰줍니다.
- This project is governed by the GPLv3 License. Derivative models, framework re-engineering fork scripts, and computational extensions of identical architecture cannot be made proprietary; they must be fully disclosed and distributed to the public under the exact same open-source licensing terms.