LayoutTensor ๋ฒ์
๊ฐ์
1D LayoutTensor a์ b๋ฅผ ๋ธ๋ก๋์บ์คํธ๋ก ๋ํด 2D LayoutTensor output์ ์ ์ฅํ๋ ์ปค๋์ ๊ตฌํํด ๋ณด์ธ์.
์ฐธ๊ณ : ์ค๋ ๋ ์๊ฐ ํ๋ ฌ์ ์์น ์๋ณด๋ค ๋ง์ต๋๋ค.
ํต์ฌ ๊ฐ๋
์ด ํผ์ฆ์์ ๋ฐฐ์ธ ๋ด์ฉ:
- ๋ธ๋ก๋์บ์คํธ ์ฐ์ฐ์
LayoutTensor์ฌ์ฉํ๊ธฐ - ์๋ก ๋ค๋ฅธ ํ ์ ํฌ๊ธฐ ๋ค๋ฃจ๊ธฐ
LayoutTensor๋ก 2D ์ธ๋ฑ์ฑ ์ฒ๋ฆฌํ๊ธฐ
ํต์ฌ์ LayoutTensor๊ฐ ์๋ก ๋ค๋ฅธ ํ
์ ํฌ๊ธฐ \((1, n)\)์ \((n, 1)\)์ \((n,n)\)์ผ๋ก ์์ฐ์ค๋ฝ๊ฒ ๋ธ๋ก๋์บ์คํธํ ์ ์๋ค๋ ์ ์
๋๋ค. ๊ทธ๋ฌ๋ฉด์๋ ๊ฒฝ๊ณ ๊ฒ์ฌ๋ ์ฌ์ ํ ํ์ํฉ๋๋ค.
- ํ ์ ํฌ๊ธฐ: ์ ๋ ฅ ๋ฒกํฐ์ ํฌ๊ธฐ๋ \((1, n)\)๊ณผ \((n, 1)\)
- ๋ธ๋ก๋์บ์คํธ: ๋ ์ฐจ์์ ๊ฒฐํฉํด \((n,n)\) ์ถ๋ ฅ ์์ฑ
- ๊ฐ๋ ์กฐ๊ฑด: ์ถ๋ ฅ ํฌ๊ธฐ์ ๋ํ ๊ฒฝ๊ณ ๊ฒ์ฌ๋ ์ฌ์ ํ ํ์
- ์ค๋ ๋ ๋ฒ์: ํ ์ ์์ \((2 \times 2)\)๋ณด๋ค ์ค๋ ๋ \((3 \times 3)\)๊ฐ ๋ง์
์์ฑํ ์ฝ๋
comptime SIZE = 2
comptime BLOCKS_PER_GRID = 1
comptime THREADS_PER_BLOCK = (3, 3)
comptime dtype = DType.float32
comptime out_layout = Layout.row_major(SIZE, SIZE)
comptime a_layout = Layout.row_major(1, SIZE)
comptime b_layout = Layout.row_major(SIZE, 1)
fn broadcast_add[
out_layout: Layout,
a_layout: Layout,
b_layout: Layout,
](
output: LayoutTensor[dtype, out_layout, MutAnyOrigin],
a: LayoutTensor[dtype, a_layout, ImmutAnyOrigin],
b: LayoutTensor[dtype, b_layout, ImmutAnyOrigin],
size: UInt,
):
row = thread_idx.y
col = thread_idx.x
# FILL ME IN (roughly 2 lines)
์ ์ฒด ์ฝ๋ ๋ณด๊ธฐ: problems/p05/p05_layout_tensor.mojo
ํ
- 2D ์ธ๋ฑ์ค ๊ฐ์ ธ์ค๊ธฐ:
row = thread_idx.y,col = thread_idx.x - ๊ฐ๋ ์ถ๊ฐ:
if row < size and col < size - ๊ฐ๋ ๋ด๋ถ: LayoutTensor๋ก
a์b๊ฐ์ ์ด๋ป๊ฒ ๋ธ๋ก๋์บ์คํธํ ์ง ์๊ฐํด ๋ณด์ธ์
์ฝ๋ ์คํ
์๋ฃจ์ ์ ํ ์คํธํ๋ ค๋ฉด ํฐ๋ฏธ๋์์ ๋ค์ ๋ช ๋ น์ด๋ฅผ ์คํํ์ธ์:
pixi run p05_layout_tensor
pixi run -e amd p05_layout_tensor
pixi run -e apple p05_layout_tensor
uv run poe p05_layout_tensor
ํผ์ฆ์ ์์ง ํ์ง ์์๋ค๋ฉด ์ถ๋ ฅ์ด ๋ค์๊ณผ ๊ฐ์ด ๋ํ๋ฉ๋๋ค:
out: HostBuffer([0.0, 0.0, 0.0, 0.0])
expected: HostBuffer([1.0, 2.0, 11.0, 12.0])
์๋ฃจ์
fn broadcast_add[
out_layout: Layout,
a_layout: Layout,
b_layout: Layout,
](
output: LayoutTensor[dtype, out_layout, MutAnyOrigin],
a: LayoutTensor[dtype, a_layout, ImmutAnyOrigin],
b: LayoutTensor[dtype, b_layout, ImmutAnyOrigin],
size: UInt,
):
row = thread_idx.y
col = thread_idx.x
if row < size and col < size:
output[row, col] = a[0, col] + b[row, 0]
LayoutTensor ๋ธ๋ก๋์บ์คํธ์ GPU ์ค๋ ๋ ๋งคํ์ ํต์ฌ ๊ฐ๋ ์ ๋ณด์ฌ์ฃผ๋ ์๋ฃจ์ ์ ๋๋ค:
-
์ค๋ ๋์์ ํ๋ ฌ๋ก ๋งคํ
thread_idx.y๋ก ํ,thread_idx.x๋ก ์ด์ ์ ๊ทผ- ์์ฐ์ค๋ฌ์ด 2D ์ธ๋ฑ์ฑ์ด ์ถ๋ ฅ ํ๋ ฌ ๊ตฌ์กฐ์ ์ผ์น
- ์ด๊ณผ ์ค๋ ๋(3ร3 ๊ทธ๋ฆฌ๋)๋ ๊ฒฝ๊ณ ๊ฒ์ฌ๋ก ์ฒ๋ฆฌ
-
๋ธ๋ก๋์บ์คํธ ์๋ ๋ฐฉ์
- ์
๋ ฅ
a์ ํฌ๊ธฐ๋(1,n):a[0,col]์ด ํ์ ๊ฐ๋ก์ง๋ฌ ๋ธ๋ก๋์บ์คํธ - ์
๋ ฅ
b์ ํฌ๊ธฐ๋(n,1):b[row,0]์ด ์ด์ ๊ฐ๋ก์ง๋ฌ ๋ธ๋ก๋์บ์คํธ - ์ถ๋ ฅ์ ํฌ๊ธฐ๋
(n,n): ๊ฐ ์์๋ ํด๋น ๋ธ๋ก๋์บ์คํธ ๊ฐ๋ค์ ํฉ
[ a0 a1 ] + [ b0 ] = [ a0+b0 a1+b0 ] [ b1 ] [ a0+b1 a1+b1 ] - ์
๋ ฅ
-
๊ฒฝ๊ณ ๊ฒ์ฌ
- ๊ฐ๋ ์กฐ๊ฑด
row < size and col < size๋ก ๋ฒ์ ์ด๊ณผ ์ ๊ทผ ๋ฐฉ์ง - ํ๋ ฌ ๋ฒ์์ ์ด๊ณผ ์ค๋ ๋๋ฅผ ํจ์จ์ ์ผ๋ก ์ฒ๋ฆฌ
- ๋ธ๋ก๋์บ์คํธ ๋๋ถ์
a์b์ ๋ํ ๋ณ๋ ๊ฒ์ฌ ๋ถํ์
- ๊ฐ๋ ์กฐ๊ฑด
์ด ํจํด์ ์ดํ ํผ์ฆ์์ ๋ค๋ฃฐ ๋ ๋ณต์กํ ํ ์ ์ฐ์ฐ์ ๊ธฐ์ด๊ฐ ๋ฉ๋๋ค.