apple-silicon

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Apple Silicon

Apple Silicon

Purpose

用途

Guide agents through Apple Silicon (M-series) development: unified memory architecture, AMX matrix coprocessor access via Accelerate, Metal Performance Shaders for GPU compute,
sysctl
hardware queries, Instruments profiling, command-line leak tools, Rosetta 2 translation behavior, and 16KB page size implications.
指导Agent进行Apple Silicon(M系列)开发,内容涵盖:统一内存架构、通过Accelerate框架访问AMX矩阵协处理器、用于GPU计算的Metal Performance Shaders、
sysctl
硬件查询、Instruments性能分析、命令行泄漏检测工具、Rosetta 2转译行为以及16KB页大小的影响。

When to Use

适用场景

  • Optimizing native ARM64 apps on macOS for M1/M2/M3/M4
  • Using GPU/NPU compute without discrete GPU PCIe transfers
  • Profiling memory and CPU with Instruments or command-line tools
  • Understanding Rosetta 2 compatibility for x86 binaries
  • Adapting code for 16KB page size on Apple Silicon
  • Accessing matrix acceleration via Accelerate/vDSP/BLAS
  • 针对M1/M2/M3/M4优化macOS上的原生ARM64应用
  • 无需独立GPU PCIe传输即可使用GPU/NPU计算
  • 使用Instruments或命令行工具分析内存与CPU性能
  • 了解x86二进制文件的Rosetta 2兼容性
  • 为Apple Silicon的16KB页大小适配代码
  • 通过Accelerate/vDSP/BLAS访问矩阵加速能力

Workflow

工作流程

1. Unified memory architecture

1. 统一内存架构

Apple Silicon SoC
├── CPU cores (P + E cores)
├── GPU cores
├── Neural Engine (NPU)
└── Unified DRAM — single address space, no PCIe copy
Implications:
  • cudaMemcpy
    equivalent is unnecessary for CPU↔GPU on Metal
  • Memory bandwidth shared across agents — profile holistically
  • Process memory includes all unified allocations
Apple Silicon SoC
├── CPU cores (P + E cores)
├── GPU cores
├── Neural Engine (NPU)
└── Unified DRAM — single address space, no PCIe copy
影响说明:
  • 在Metal架构下,CPU与GPU之间无需类似
    cudaMemcpy
    的内存拷贝操作
  • 内存带宽由各计算单元共享,需从整体角度进行性能分析
  • 进程内存包含所有统一内存分配

2. Hardware information

2. 硬件信息

bash
undefined
bash
undefined

CPU and chip info

CPU and chip info

sysctl -n machdep.cpu.brand_string sysctl hw.physicalcpu hw.logicalcpu sysctl hw.memsize
sysctl -n machdep.cpu.brand_string sysctl hw.physicalcpu hw.logicalcpu sysctl hw.memsize

ARM64 features (keys vary by chip — grep if specific FEAT_* is missing)

ARM64 features (keys vary by chip — grep if specific FEAT_* is missing)

sysctl -a hw.optional.arm 2>/dev/null | grep -iE 'sve|bf16|mte'
sysctl -a hw.optional.arm 2>/dev/null | grep -iE 'sve|bf16|mte'

Cache line size

Cache line size

sysctl hw.cachelinesize
sysctl hw.cachelinesize

Page size (16KB on macOS Apple Silicon)

Page size (16KB on macOS Apple Silicon)

sysctl hw.pagesize # 16384 getconf PAGESIZE
undefined
sysctl hw.pagesize # 16384 getconf PAGESIZE
undefined

3. 16KB page size considerations

3. 16KB页大小注意事项

macOS on Apple Silicon uses 16KB pages (not 4KB):
c
// Align hot buffers to page size
size_t page = sysconf(_SC_PAGESIZE);  // 16384
void *buf = aligned_alloc(page, size);

// mmap alignment must be page-aligned
mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
Impact:
  • posix_memalign
    minimum alignment often 16KB for large allocs
  • JVM/Go runtimes auto-tune; custom allocators must adapt
  • Test on device — x86 CI may use 4KB pages
Apple Silicon上的macOS采用16KB页(而非4KB):
c
// Align hot buffers to page size
size_t page = sysconf(_SC_PAGESIZE);  // 16384
void *buf = aligned_alloc(page, size);

// mmap alignment must be page-aligned
mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
影响:
  • 对于大内存分配,
    posix_memalign
    的最小对齐要求通常为16KB
  • JVM/Go运行时会自动调整,自定义内存分配器需做适配
  • 需在真机上测试——x86架构的CI环境可能使用4KB页

4. AMX (Apple Matrix Coprocessor)

4. AMX(苹果矩阵协处理器)

AMX is undocumented at ISA level; access through frameworks:
c
// Accelerate framework — uses AMX internally for matrix ops
#include <Accelerate/Accelerate.h>

void matrix_multiply(const float *A, const float *B, float *C,
                     int M, int N, int K) {
    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
                M, N, K, 1.0f, A, K, B, N, 0.0f, C, N);
}
bash
undefined
AMX在指令集架构(ISA)层面未公开文档,需通过官方框架访问:
c
// Accelerate framework — uses AMX internally for matrix ops
#include <Accelerate/Accelerate.h>

void matrix_multiply(const float *A, const float *B, float *C,
                     int M, int N, int K) {
    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
                M, N, K, 1.0f, A, K, B, N, 0.0f, C, N);
}
bash
undefined

Link Accelerate (default on macOS)

Link Accelerate (default on macOS)

clang -framework Accelerate -o gemm gemm.c -lcblas

For custom AMX kernels: study community reverse engineering or use Metal Performance Shaders as supported path.
clang -framework Accelerate -o gemm gemm.c -lcblas

若需自定义AMX内核:可参考社区逆向工程成果,或使用官方支持的Metal Performance Shaders方案。

5. Metal Performance Shaders (MPS)

5. Metal Performance Shaders(MPS)

objc
// Objective-C / Swift — GPU compute via MPS
#import <Metal/Metal.h>
#import <MetalPerformanceShaders/MetalPerformanceShaders.h>

id<MTLDevice> device = MTLCreateSystemDefaultDevice();
id<MTLCommandQueue> queue = [device newCommandQueue];

MPSMatrixMultiplication *gemm = [[MPSMatrixMultiplication alloc]
    initWithDevice:device transposeLeft:NO transposeRight:NO
    resultRows:M columns:N interiorColumns:K alpha:1.0 beta:0.0];
Metal provides unified memory path to GPU — no explicit copy for buffers allocated with
MTLResourceStorageModeShared
.
objc
// Objective-C / Swift — GPU compute via MPS
#import <Metal/Metal.h>
#import <MetalPerformanceShaders/MetalPerformanceShaders.h>

id<MTLDevice> device = MTLCreateSystemDefaultDevice();
id<MTLCommandQueue> queue = [device newCommandQueue];

MPSMatrixMultiplication *gemm = [[MPSMatrixMultiplication alloc]
    initWithDevice:device transposeLeft:NO transposeRight:NO
    resultRows:M columns:N interiorColumns:K alpha:1.0 beta:0.0];
Metal提供了访问GPU的统一内存路径——使用
MTLResourceStorageModeShared
分配的缓冲区无需显式内存拷贝。

6. Instruments profiling

6. Instruments性能分析

bash
undefined
bash
undefined

Command-line Instruments (xctrace)

Command-line Instruments (xctrace)

xctrace record --template 'Time Profiler' --launch -- /path/to/app xctrace record --template 'Allocations' --launch -- /path/to/app xctrace record --template 'Leaks' --launch -- /path/to/app xctrace export --input trace.trace --toc

| Template | Use |
|----------|-----|
| Time Profiler | CPU hotspots, P/E core usage |
| Allocations | Heap growth, allocation call trees |
| Leaks | Retained memory |
| System Trace | Thread scheduling, syscalls |

GUI: Xcode → Product → Profile (⌘I)
xctrace record --template 'Time Profiler' --launch -- /path/to/app xctrace record --template 'Allocations' --launch -- /path/to/app xctrace record --template 'Leaks' --launch -- /path/to/app xctrace export --input trace.trace --toc

| 模板 | 用途 |
|----------|-----|
| Time Profiler | CPU热点分析、性能核/能效核使用情况 |
| Allocations | 堆内存增长分析、内存分配调用栈 |
| Leaks | 内存泄漏检测(留存内存分析) |
| System Trace | 线程调度、系统调用跟踪 |

图形界面操作:Xcode → Product → Profile (⌘I)

7. Command-line debugging tools

7. 命令行调试工具

bash
undefined
bash
undefined

Process memory map

Process memory map

vmmap <pid>
vmmap <pid>

Heap analysis

Heap analysis

heap <pid> heap <pid> -addresses all # all allocations
heap <pid> heap <pid> -addresses all # all allocations

Leak detection

Leak detection

leaks <pid> leaks --list <pid>
leaks <pid> leaks --list <pid>

Sample call stacks

Sample call stacks

sample <pid> 5 -file sample.txt
undefined
sample <pid> 5 -file sample.txt
undefined

8. Rosetta 2 translation

8. Rosetta 2转译

bash
undefined
bash
undefined

Check if process runs under Rosetta

Check if process runs under Rosetta

sysctl sysctl.proc_translated # 1 = translated x86
sysctl sysctl.proc_translated # 1 = translated x86

Force arch

Force arch

arch -arm64 ./native_binary arch -x86_64 ./x86_binary
arch -arm64 ./native_binary arch -x86_64 ./x86_binary

Universal binary info

Universal binary info

lipo -info myapp file myapp

| Runs native ARM64 | Runs under Rosetta |
|-------------------|-------------------|
| ARM64 build | x86_64-only binary |
| `-arch arm64` compile | Downloaded Intel-only app |

Rosetta 2: translates x86_64 to ARM64 with JIT cache. AVX/AVX2 translated but may be slower. Not for kernel extensions or VM guests.
lipo -info myapp file myapp

| 原生ARM64运行 | Rosetta转译运行 |
|-------------------|-------------------|
| ARM64构建版本 | 仅x86_64架构的二进制文件 |
| 使用`-arch arm64`编译的程序 | 下载的仅支持Intel架构的应用 |

Rosetta 2:通过JIT缓存将x86_64指令转译为ARM64指令。AVX/AVX2指令可被转译,但性能可能下降。不适用于内核扩展或虚拟机客户机。

9. Memory tagging (ARM MTE)

9. 内存标记(ARM MTE)

Future Apple hardware may expose MTE — monitor via:
bash
sysctl hw.optional.arm.FEAT_MTE  # when available
Prepare with pointer authentication already on ARM64e Apple platforms.
未来的苹果硬件可能支持MTE,可通过以下命令检测:
bash
sysctl hw.optional.arm.FEAT_MTE  # when available
目前Apple平台的ARM64e架构已支持指针认证,可提前做好相关准备。

10. Build and perf tips

10. 构建与性能优化技巧

bash
undefined
bash
undefined

Native optimized build

Native optimized build

clang -arch arm64 -O3 -mcpu=apple-m1 -o app app.c
clang -arch arm64 -O3 -mcpu=apple-m1 -o app app.c

Use -mcpu matching target: apple-m1, apple-m2, apple-m3, apple-m4

Use -mcpu matching target: apple-m1, apple-m2, apple-m3, apple-m4

P/E core awareness — dispatch heavy work to performance cores

P/E core awareness — dispatch heavy work to performance cores

pthread_set_qos_class_self_np(QOS_CLASS_USER_INITIATED, 0);

pthread_set_qos_class_self_np(QOS_CLASS_USER_INITIATED, 0);

undefined
undefined

Common Problems

常见问题

SymptomCauseFix
mmap fails with EINVAL4KB alignment on 16KB systemAlign to
sysconf(_SC_PAGESIZE)
Slow x86 binaryRosetta overheadShip universal or arm64-only build
Metal buffer nilSimulator vs deviceTest GPU on real hardware
Accelerate wrong resultsRow/column major mismatchCheck BLAS leading dimensions
Instruments empty traceSandbox/permissionsRun from Xcode or sign app
sysctl not foundWrong key name`sysctl -a
现象原因解决方案
mmap调用失败并返回EINVAL在16KB页系统上使用了4KB对齐对齐到
sysconf(_SC_PAGESIZE)
返回的页大小
x86二进制文件运行缓慢Rosetta转译开销发布通用二进制版本或仅支持arm64的版本
Metal缓冲区为nil模拟器与真机差异在真实硬件上测试GPU功能
Accelerate计算结果错误行优先/列优先格式不匹配检查BLAS的leading dimensions参数
Instruments生成的跟踪文件为空沙箱/权限问题通过Xcode运行或为应用签名
sysctl查询不到对应项键名错误使用`sysctl -a

Related Skills

相关技能

  • skills/low-level-programming/assembly-arm
    — Darwin ABI, AArch64
  • skills/platform/arm-sve
    — SVE2 on M4+
  • skills/gpu/cuda
    — NVIDIA not on Apple Silicon; use Metal instead
  • skills/profilers/heaptrack
    — cross-platform heap profiling concepts
  • skills/compilers/clang
    — Apple Clang flags
  • skills/low-level-programming/cpu-cache-opt
    — cache optimization on unified memory
  • skills/low-level-programming/assembly-arm
    — Darwin ABI、AArch64架构
  • skills/platform/arm-sve
    — M4及以上芯片的SVE2支持
  • skills/gpu/cuda
    — Apple Silicon不支持NVIDIA,需使用Metal替代
  • skills/profilers/heaptrack
    — 跨平台堆内存性能分析概念
  • skills/compilers/clang
    — Apple Clang编译选项
  • skills/low-level-programming/cpu-cache-opt
    — 统一内存架构下的缓存优化