본문 바로가기
C.W.K.
Stream
Lesson 02 of 07 · published

배열과 자료형, 통합 메모리가 만드는 차이

~14 min · arrays, dtypes, unified-memory

Level 0호기심
0 XP0/51 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

mx.array로 시작해

MLX 배열은 통합 메모리에 놓이는 자료형이 있는 N차원 버퍼야. Python 목록, NumPy 배열, 다른 MLX 배열로 만들 수 있고 shape, dtype, ndim을 제공해. NumPy 배열이나 PyTorch 텐서를 써봤다면 첫 30초는 똑같이 느껴질 거야.

차이는 작아 보여도 설계 전체를 드러내. 어디에도 device 인자가 없어. 다음 레슨에도, 그다음에도 계속 안 나올 거야.

자료형은 과학 전반보다 머신러닝에 맞췄어

NumPy는 범용 과학 계산 도구라 complex128, datetime64, 구조화 레코드처럼 아주 넓은 숫자 체계를 지원해. MLX의 자료형은 머신러닝 작업에 맞춰 좁혔어. mlx 0.31.x에서는 기본인 float32float16, bfloat16, int8 / int16 / int32 / int64, uint8 / uint16 / uint32 / uint64, bool, 몇 가지 복소수형을 지원해. 날짜형, 구조화 레코드, 확장 정밀도는 없어.

이건 결함보다 의도된 선택에 가까워. 지원 범위가 작으면 커널 코드가 단순해지고, 최적화할 갈래와 관리할 모서리 사례도 줄어. complex128이 꼭 필요하다면 MLX가 아닌 다른 도구가 맞을 가능성이 커.

배열은 처음부터 통합 메모리에 살아

모든 mx.array는 기본적으로 통합 메모리에 놓여. Apple Silicon에서 mx.default_device()Device(gpu, 0)를 돌려주지만, foundations.lesson2에서 봤듯 이 값은 다음 연산을 어느 장치가 맡을지 알려주는 표지야. 바이트가 사는 위치가 아니야. 바이트는 처음부터 끝까지 하나의 공유 메모리 풀에 있어.

자료형 승격은 한 번 더 확인해

int32_array + float32_array처럼 서로 다른 자료형을 섞으면 MLX는 대체로 NumPy와 같은 규칙으로 더 넓은 자료형으로 올려. 언제나 같지는 않아. 특히 실수형인 학습 가중치와 정수 색인을 섞을 때는 의도한 지점에서 .astype(mx.float32)를 명시하는 습관이 안전해. 암묵적 승격은 한 시간짜리 디버깅을 만나기 전까지만 편하거든.

Code

배열 만들기 — NumPy에서 익힌 모양 그대로·python
import mlx.core as mx

a = mx.array([1, 2, 3, 4])
b = mx.array([1.5, 2.5, 3.5, 4.5])
c = mx.zeros((3, 4))
d = mx.ones((2, 2), dtype=mx.float16)

print('a:', a, 'dtype:', a.dtype, 'shape:', a.shape, 'size:', a.size, 'ndim:', a.ndim)
print('b:', b, 'dtype:', b.dtype)
print('c shape:', c.shape, 'dtype:', c.dtype)
print('d:', d, 'dtype:', d.dtype)

# Verified output (2026-05-03):
#   a: array([1, 2, 3, 4], dtype=int32) dtype: mlx.core.int32 shape: (4,) size: 4 ndim: 1
#   b: array([1.5, 2.5, 3.5, 4.5], dtype=float32) dtype: mlx.core.float32
#   c shape: (3, 4) dtype: mlx.core.float32
#   d: array([[1, 1], [1, 1]], dtype=float16) dtype: mlx.core.float16
자료형을 명시적으로 바꾸기 — `.astype`·python
import mlx.core as mx

a = mx.array([1, 2, 3, 4])               # inferred → int32
print('a       :', a, a.dtype)

a_f = a.astype(mx.float32)
print('a.astype:', a_f, a_f.dtype)        # → float32

# Verified:
#   a       : array([1, 2, 3, 4], dtype=int32) mlx.core.int32
#   a.astype: array([1, 2, 3, 4], dtype=float32) mlx.core.float32

# Be explicit when you mean float — implicit promotion to float32
# happens in arithmetic anyway, but .astype documents your intent.
기본 장치와 통합 메모리 확인·python
import mlx.core as mx

# The default 'device' is just a label about where compute runs next.
# All bytes live in the unified-memory pool either way.
print('default device:', mx.default_device())   # → Device(gpu, 0) on Apple Silicon

x = mx.array([1.0, 2.0, 3.0])
print('x lives in :', mx.default_device(), '— but the bytes are in unified memory.')

External links

Exercise

배열 다섯 개를 직접 만들어. int32, float32, float16, bool을 하나씩 만들고 모양이 (3, 5)인 0 배열도 하나 만들어. 각각의 dtype, shape, ndim, size를 출력해. 그중 둘을 골라 +* 연산을 하고 결과 자료형을 확인해. 더 높은 정밀도로 승격되는 조합과 그렇지 않은 조합을 하나씩 시도한 뒤 알아낸 점을 두 문장으로 적어.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.