张量谜题
- 作者:Sasha Rush - srush_nlp (与Marcos Treviso合作)
在学习像PyTorch或Numpy这样的张量编程语言时,很容易依赖标准库(或者更诚实地说,依赖StackOverflow)来寻找各种神奇的函数。但实际上,张量语言非常强大,你可以通过基本原理和巧妙运用广播机制来完成大多数任务。
这是一个包含21个张量谜题的集合。就像国际象棋谜题一样,这些谜题并不是为了模拟真实程序的复杂性,而是为了在简化的环境中进行练习。每个谜题都要求你在不使用魔法的情况下重新实现NumPy标准库中的一个函数。
我建议在Colab中运行。点击这里并复制笔记本以开始。
如果你感兴趣,这里还有一个解答谜题的YouTube视频教程
!pip install -qqq torchtyping hypothesis pytest git+https://github.com/danoneata/chalk@srush-patch-1
!wget -q https://github.com/srush/Tensor-Puzzles/raw/main/lib.py
from lib import draw_examples, make_test, run_test
import torch
import numpy as np
from torchtyping import TensorType as TT
tensor = torch.tensor
规则
- 这些谜题主要关于广播。请记住这条规则。
-
每个谜题需要用1行代码(<80列)解决。
-
你可以使用@、算术运算、比较运算、
shape
、任何索引(如a[:j]
、a[:, None]
、a[arange(10)]
)以及之前谜题中的函数。 -
你不能使用其他任何东西。不允许使用
view
、sum
、take
、squeeze
、tensor
。 -
你可以从这两个函数开始:
def arange(i: int):
"使用此函数来替代for循环。"
return torch.tensor(range(i))
draw_examples("arange", [{"" : arange(i)} for i in [5, 3, 9]])
# 广播示例
examples = [(arange(4), arange(5)[:, None]) ,
(arange(3)[:, None], arange(2))]
draw_examples("broadcast", [{"a": a, "b":b, "ret": a + b} for a, b in examples])
def where(q, a, b):
"使用此函数来替代if语句。"
return (q * a) + (~q) * b
# 在图表中,橙色表示正/真,白色表示零/假,蓝色表示负。
examples = [(tensor([False]), tensor([10]), tensor([0])),
(tensor([False, True]), tensor([1, 1]), tensor([-10, 0])),
(tensor([False, True]), tensor([1]), tensor([-10, 0])),
(tensor([[False, True], [True, False]]), tensor([1]), tensor([-10, 0])),
(tensor([[False, True], [True, False]]), tensor([[0], [10]]), tensor([-10, 0])),
]
draw_examples("where", [{"q": q, "a":a, "b":b, "ret": where(q, a, b)} for q, a, b in examples])
谜题1 - ones
计算ones - 全为1的向量。
def ones_spec(out):
for i in range(len(out)):
out[i] = 1
def ones(i: int) -> TT["i"]:
raise NotImplementedError
test_ones = make_test("one", ones, ones_spec, add_sizes=["i"])
# run_test(test_ones)
谜题2 - sum
计算sum - 向量的和。
def sum_spec(a, out):
out[0] = 0
for i in range(len(a)):
out[0] += a[i]
def sum(a: TT["i"]) -> TT[1]:
raise NotImplementedError
test_sum = make_test("sum", sum, sum_spec)
# run_test(test_sum)
谜题3 - outer
计算outer - 两个向量的外积。
def outer_spec(a, b, out):
for i in range(len(out)):
for j in range(len(out[0])):
out[i][j] = a[i] * b[j]
def outer(a: TT["i"], b: TT["j"]) -> TT["i", "j"]:
raise NotImplementedError
test_outer = make_test("outer", outer, outer_spec)
# run_test(test_outer)
谜题4 - diag
计算diag - 方阵的对角线向量。
def diag_spec(a, out):
for i in range(len(a)):
out[i] = a[i][i]
def diag(a: TT["i", "i"]) -> TT["i"]:
raise NotImplementedError
test_diag = make_test("diag", diag, diag_spec)
# run_test(test_diag)
谜题5 - eye
计算eye - 单位矩阵。
def eye_spec(out):
for i in range(len(out)):
out[i][i] = 1
def eye(j: int) -> TT["j", "j"]:
raise NotImplementedError
test_eye = make_test("eye", eye, eye_spec, add_sizes=["j"])
# run_test(test_eye)
谜题6 - triu
计算triu - 上三角矩阵。
def triu_spec(out):
for i in range(len(out)):
for j in range(len(out)):
if i <= j:
out[i][j] = 1
else:
out[i][j] = 0
def triu(j: int) -> TT["j", "j"]:
raise NotImplementedError
test_triu = make_test("triu", triu, triu_spec, add_sizes=["j"])
# run_test(test_triu)
谜题7 - cumsum
计算cumsum - 累积和。
def cumsum_spec(a, out):
total = 0
for i in range(len(out)):
out[i] = total + a[i]
total += a[i]
def cumsum(a: TT["i"]) -> TT["i"]:
raise NotImplementedError
test_cumsum = make_test("cumsum", cumsum, cumsum_spec)
# run_test(test_cumsum)
谜题8 - diff
计算diff - 运行差值。
def diff_spec(a, out):
out[0] = a[0]
for i in range(1, len(out)):
out[i] = a[i] - a[i - 1]
def diff(a: TT["i"], i: int) -> TT["i"]:
raise NotImplementedError
test_diff = make_test("diff", diff, diff_spec, add_sizes=["i"])
# run_test(test_diff)
谜题9 - vstack
计算vstack - 两个向量的矩阵
def vstack_spec(a, b, out):
for i in range(len(out[0])):
out[0][i] = a[i]
out[1][i] = b[i]
def vstack(a: TT["i"], b: TT["i"]) -> TT[2, "i"]:
raise NotImplementedError
test_vstack = make_test("vstack", vstack, vstack_spec)
# run_test(test_vstack)
谜题10 - roll
计算roll - 循环移动1个位置的向量。
def roll_spec(a, out):
for i in range(len(out)):
if i + 1 < len(out):
out[i] = a[i + 1]
else:
out[i] = a[i + 1 - len(out)]
def roll(a: TT["i"], i: int) -> TT["i"]:
raise NotImplementedError
test_roll = make_test("roll", roll, roll_spec, add_sizes=["i"])
# run_test(test_roll)
谜题11 - flip
计算flip - 反转的向量
def flip_spec(a, out):
for i in range(len(out)):
out[i] = a[len(out) - i - 1]
def flip(a: TT["i"], i: int) -> TT["i"]:
raise NotImplementedError
test_flip = make_test("flip", flip, flip_spec, add_sizes=["i"])
# run_test(test_flip)
谜题12 - compress
计算compress - 只保留掩码条目(左对齐)。
def compress_spec(g, v, out):
j = 0
for i in range(len(g)):
if g[i]:
out[j] = v[i]
j += 1
def compress(g: TT["i", bool], v: TT["i"], i:int) -> TT["i"]:
raise NotImplementedError
test_compress = make_test("compress", compress, compress_spec, add_sizes=["i"])
# run_test(test_compress)
谜题13 - pad_to
计算pad_to - 通过消除或添加0来改变向量的大小。
def pad_to_spec(a, out):
for i in range(min(len(out), len(a))):
out[i] = a[i]
def pad_to(a: TT["i"], i: int, j: int) -> TT["j"]:
raise NotImplementedError
test_pad_to = make_test("pad_to", pad_to, pad_to_spec, add_sizes=["i", "j"])
# run_test(test_pad_to)
谜题14 - sequence_mask
计算sequence_mask - 每批填充到指定长度。
def sequence_mask_spec(values, length, out):
for i in range(len(out)):
for j in range(len(out[0])):
if j < length[i]:
out[i][j] = values[i][j]
else:
out[i][j] = 0
def sequence_mask(values: TT["i", "j"], length: TT["i", int]) -> TT["i", "j"]:
raise NotImplementedError
def constraint_set_length(d):
d["length"] = d["length"] % d["values"].shape[1]
return d
test_sequence = make_test("sequence_mask",
sequence_mask, sequence_mask_spec, constraint=constraint_set_length
)
# run_test(test_sequence)
谜题15 - bincount
计算bincount - 统计每个元素出现的次数。
def bincount_spec(a, out):
for i in range(len(a)):
out[a[i]] += 1
def bincount(a: TT["i"], j: int) -> TT["j"]:
raise NotImplementedError
def constraint_set_max(d):
d["a"] = d["a"] % d["return"].shape[0]
return d
test_bincount = make_test("bincount",
bincount, bincount_spec, add_sizes=["j"], constraint=constraint_set_max
)
# run_test(test_bincount)
谜题16 - scatter_add
计算scatter_add - 将链接到同一位置的值相加。
def scatter_add_spec(values, link, out):
for j in range(len(values)):
out[link[j]] += values[j]
def scatter_add(values: TT["i"], link: TT["i"], j: int) -> TT["j"]:
raise NotImplementedError
def constraint_set_max(d):
d["link"] = d["link"] % d["return"].shape[0]
return d
test_scatter_add = make_test("scatter_add",
scatter_add, scatter_add_spec, add_sizes=["j"], constraint=constraint_set_max
)
# run_test(test_scatter_add)
谜题17 - flatten
计算flatten
def flatten_spec(a, out):
k = 0
for i in range(len(a)):
for j in range(len(a[0])):
out[k] = a[i][j]
k += 1
def flatten(a: TT["i", "j"], i:int, j:int) -> TT["i * j"]:
raise NotImplementedError
test_flatten = make_test("flatten", flatten, flatten_spec, add_sizes=["i", "j"])
# run_test(test_flatten)
谜题18 - linspace
计算linspace
def linspace_spec(i, j, out):
for k in range(len(out)):
out[k] = float(i + (j - i) * k / max(1, len(out) - 1))
def linspace(i: TT[1], j: TT[1], n: int) -> TT["n", float]:
raise NotImplementedError
test_linspace = make_test("linspace", linspace, linspace_spec, add_sizes=["n"])
# run_test(test_linspace)
谜题19 - heaviside
def heaviside_spec(a, b, out):
for k in range(len(out)):
if a[k] == 0:
out[k] = b[k]
else:
out[k] = int(a[k] > 0)
def heaviside(a: TT["i"], b: TT["i"]) -> TT["i"]:
raise NotImplementedError
test_heaviside = make_test("heaviside", heaviside, heaviside_spec)
# run_test(test_heaviside)
谜题20 - repeat (1d)
计算repeat
def repeat_spec(a, d, out):
for i in range(d[0]):
for k in range(len(a)):
out[i][k] = a[k]
def constraint_set(d):
d["d"][0] = d["return"].shape[0]
return d
def repeat(a: TT["i"], d: TT[1]) -> TT["d", "i"]:
raise NotImplementedError
test_repeat = make_test("repeat", repeat, repeat_spec, constraint=constraint_set)
谜题21 - bucketize
def bucketize_spec(v, boundaries, out):
for i, val in enumerate(v):
out[i] = 0
for j in range(len(boundaries)-1):
if val >= boundaries[j]:
out[i] = j + 1
if val >= boundaries[-1]:
out[i] = len(boundaries)
def constraint_set(d):
d["boundaries"] = np.abs(d["boundaries"]).cumsum()
return d
def bucketize(v: TT["i"], boundaries: TT["j"]) -> TT["i"]:
raise NotImplementedError
test_bucketize = make_test("bucketize", bucketize, bucketize_spec,
constraint=constraint_set)
速度挑战模式!
你能将每个函数尽可能缩短到多少?
import inspect
fns = (ones, sum, outer, diag, eye, triu, cumsum, diff, vstack, roll, flip,
compress, pad_to, sequence_mask, bincount, scatter_add)
for fn in fns:
lines = [l for l in inspect.getsource(fn).split("\n") if not l.strip().startswith("#")]
if len(lines) > 3:
print(fn.__name__, len(lines[2]), "(超过1行)")
else:
print(fn.__name__, len(lines[1]))
ones 29
sum 29
outer 29
diag 29
eye 29
triu 29
cumsum 29
diff 29
vstack 29
roll 29
flip 29
compress 29
pad_to 29
sequence_mask 29
bincount 29
scatter_add 29