WeixiangYan/CodeTransOcean huggingface dataset:
MXNet: from mxnet import np, npx
from mxnet.gluon import nn
npx.set_np()
x = np.arange(4)
npx.save('x-file', x)
x2 = npx.load('x-file')
y = np.zeros(4)
npx.save('x-files', [x, y])
x2, y2 = npx.load('x-files')
mydict = {'x': x, 'y': y}
npx.save('mydict', mydict)
mydict2 = npx.load('mydict')
class MLP(nn.Block):
    def __init__(self, **kwargs):
        super(MLP, self).__init__(**kwargs)
        self.hidden = nn.Dense(256, activation='relu')
        self.output = nn.Dense(10)
    def forward(self, x):
        return self.output(self.hidden(x))
net = MLP()
net.initialize()
X = np.random.uniform(size=(2, 20))
Y = net(X)
net.save_parameters('mlp.params')
clone = MLP()
clone.load_parameters('mlp.params')

Paddle: import warnings
warnings.filterwarnings(action='ignore')
import paddle
from paddle import nn
from paddle.nn import functional as F
x = paddle.arange(4)
paddle.save(x, 'x-file')
x2 = paddle.load('x-file')
y = paddle.zeros([4])
paddle.save([x,y], 'x-file')
x2, y2 = paddle.load('x-file')
mydict = {'x': x, 'y': y}
paddle.save(mydict, 'mydict')
mydict2 = paddle.load('mydict')
class MLP(nn.Layer):
    def __init__(self):
        super().__init__()
        self.hidden = nn.Linear(20, 256)
        self.output = nn.Linear(256, 10)
    def forward(self, x):
        return self.output(F.relu(self.hidden(x)))
net = MLP()
X = paddle.randn(shape=[2, 20])
Y = net(X)
paddle.save(net.state_dict(), 'mlp.pdparams')
clone = MLP()
clone.set_state_dict(paddle.load('mlp.pdparams'))
clone.eval()
MXNet: from mxnet import np, npx
from mxnet.gluon import nn
npx.set_np()
npx.cpu(), npx.gpu(), npx.gpu(1)
npx.num_gpus()
def try_gpu(i=0):
    return npx.gpu(i) if npx.num_gpus() >= i + 1 else npx.cpu()
    def try_all_gpus():
devices = [npx.gpu(i) for i in range(npx.num_gpus())]
    return devices if devices else [npx.cpu()]
try_gpu(), try_gpu(10), try_all_gpus()
x = np.array([1, 2, 3])
x.ctx
X = np.ones((2, 3), ctx=try_gpu())
Y = np.random.uniform(size=(2, 3), ctx=try_gpu(1))
Z = X.copyto(try_gpu(1))
Z.as_in_ctx(try_gpu(1)) is Z
net = nn.Sequential()
net.add(nn.Dense(1))
net.initialize(ctx=try_gpu())
net[0].weight.data().ctx

Paddle: import paddle
from paddle import nn
paddle.device.set_device("cpu"), paddle.CUDAPlace(0), paddle.CUDAPlace(1)
paddle.device.cuda.device_count()
    if paddle.device.cuda.device_count() >= i + 1:
        return paddle.CUDAPlace(i)
    return paddle.CPUPlace()
def try_all_gpus():
    devices = [paddle.CUDAPlace(i) for i in range(paddle.device.cuda.device_count())]
    return devices if devices else paddle.CPUPlace()
try_gpu(),try_gpu(10),try_all_gpus()
x = paddle.to_tensor([1, 2, 3])
x.place
X = paddle.to_tensor(paddle.ones(shape=[2, 3]), place=try_gpu())
Y = paddle.to_tensor(paddle.rand([2, 3]), place=try_gpu(1))
Z = X.cuda(1)
Z.cuda(1) is Z
net = nn.Sequential(nn.Linear(3, 1))
net=net.to(try_gpu())
net[0].weight.place
MXNet: from mxnet import autograd, np, npx from mxnet.gluon import nn
from d2l import mxnet as d2l
npx.set_np()
def corr2d(X, K):
    h, w = K.shape
    Y = np.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1))
    for i in range(Y.shape[0]):
        for j in range(Y.shape[1]):
            Y[i, j] = (X[i:i + h, j:j + w] * K).sum()
    return Y
X = np.array([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])
K = np.array([[0.0, 1.0], [2.0, 3.0]])
corr2d(X, K)
class Conv2D(nn.Block):
    def __init__(self, kernel_size, **kwargs):
        super().__init__(**kwargs)
        self.weight = self.params.get('weight', shape=kernel_size)
        self.bias = self.params.get('bias', shape=(1,))
    def forward(self, x):
        return corr2d(x, self.weight.data()) + self.bias.data()
X = np.ones((6, 8))
X[:, 2:6] = 0
K = np.array([[1.0, -1.0]])
corr2d(d2l.transpose(X), K)
conv2d = nn.Conv2D(1, kernel_size=(1, 2), use_bias=False)
conv2d.initialize()

X = X.reshape(1, 1, 6, 8)
Y = Y.reshape(1, 1, 6, 7)
lr = 3e-2
for i in range(10):
    with autograd.record():
        Y_hat = conv2d(X)
        l = (Y_hat - Y) ** 2
    l.backward()
    conv2d.weight.data()[:] -= lr * conv2d.weight.grad()
conv2d.weight.data().reshape((1, 2))

Paddle: import warningsfrom d2l import paddle as d2l
warnings.filterwarnings("ignore")
import paddle
from paddle import nn
def corr2d(X, K):
    h, w = K.shape
    Y = paddle.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1))
    for i in range(Y.shape[0]):
        for j in range(Y.shape[1]):
            Y[i, j] = (X[i:i + h, j:j + w] * K).sum()
    return Y
X = paddle.to_tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])
K = paddle.to_tensor([[0.0, 1.0], [2.0, 3.0]])
corr2d(X, K)
class Conv2D(nn.Layer):
    def __init__(self, kernel_size):
        super().__init__()
        self.weight = paddle.ParamAttr(paddle.rand(kernel_size))
        self.bias = paddle.ParamAttr(paddle.zeros(1))
    def forward(self, x):
        return corr2d(x, self.weight) + self.bias
X = paddle.ones((6, 8))
X[:, 2:6] = 0
K = paddle.to_tensor([[1.0, -1.0]])
corr2d(X.t(), K)
conv2d = nn.Conv2D(1, 1, kernel_size=(1, 2))
X = X.reshape((1, 1, 6, 8))
Y = Y.reshape((1, 1, 6, 7))
lr = 3e-2
for i in range(10):
    Y_hat = conv2d(X)
    l = (Y_hat - Y) ** 2
    conv2d.clear_gradients()
    l.sum().backward()
    with paddle.no_grad():
        conv2d.weight[:] -= lr * conv2d.weight.grad
conv2d.weight.reshape((1, 2))
MXNet: from mxnet import np, npx
from mxnet.gluon import nn
npx.set_np()
def comp_conv2d(conv2d, X):
    conv2d.initialize()
    X = X.reshape((1, 1) + X.shape)
    Y = conv2d(X)
    return Y.reshape(Y.shape[2:])
conv2d = nn.Conv2D(1, kernel_size=3, padding=1)
X = np.random.uniform(size=(8, 8))
comp_conv2d(conv2d, X).shape
conv2d = nn.Conv2D(1, kernel_size=(5, 3), padding=(2, 1))
comp_conv2d(conv2d, X).shape
conv2d = nn.Conv2D(1, kernel_size=3, padding=1, strides=2)
comp_conv2d(conv2d, X).shape
conv2d = nn.Conv2D(1, kernel_size=(3, 5), padding=(0, 1), strides=(3, 4))
comp_conv2d(conv2d, X).shape

Paddle: import warnings
warnings.filterwarnings(action='ignore')
import paddle
from paddle import nn

def comp_conv2d(conv2d, X):
    X = paddle.reshape(X, [1, 1] + X.shape)
    Y = conv2d(X)
    return Y.reshape(Y.shape[2:])
conv2d = nn.Conv2D(in_channels=1, out_channels=1, kernel_size=3, padding=1)
X = paddle.rand((8, 8))
comp_conv2d(conv2d, X).shape
conv2d = nn.Conv2D(in_channels=1, out_channels=1, kernel_size=(5, 3), padding=(2, 1))
comp_conv2d(conv2d, X).shape
conv2d = nn.Conv2D(1, 1, kernel_size=3, padding=1, stride=2)
comp_conv2d(conv2d, X).shape
conv2d = nn.Conv2D(1, 1, kernel_size=(3, 5), padding=(0, 1), stride=(3, 4))
comp_conv2d(conv2d, X).shape
MXNet: from mxnet import np, npx
from d2l import mxnet as d2l
npx.set_np()
def corr2d_multi_in(X, K):
    return sum(d2l.corr2d(x, k) for x, k in zip(X, K))
X = np.array([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]], [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]])
K = np.array([[[0.0, 1.0], [2.0, 3.0]], [[1.0, 2.0], [3.0, 4.0]]])
corr2d_multi_in(X, K)
def corr2d_multi_in_out(X, K):
    return np.stack([corr2d_multi_in(X, k) for k in K], 0)
K = np.stack((K, K + 1, K + 2), 0)
K.shape
def corr2d_multi_in_out_1x1(X, K):
    c_i, h, w = X.shape
    c_o = K.shape[0]
    X = X.reshape((c_i, h * w))
    K = K.reshape((c_o, c_i))
    Y = np.dot(K, X)
    return Y.reshape((c_o, h, w))
X = np.random.normal(0, 1, (3, 3, 3))
K = np.random.normal(0, 1, (2, 3, 1, 1))
Y1 = corr2d_multi_in_out_1x1(X, K)
Y2 = corr2d_multi_in_out(X, K)
assert float(np.abs(Y1 - Y2).sum()) < 1e-6

Paddle: import warnings
from d2l import paddle as d2l
warnings.filterwarnings("ignore")
import paddle
def corr2d_multi_in(X, K):
    return sum(d2l.corr2d(x, k) for x, k in zip(X, K))
X = paddle.to_tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]], [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]])
K = paddle.to_tensor([[[0.0, 1.0], [2.0, 3.0]], [[1.0, 2.0], [3.0, 4.0]]])
corr2d_multi_in(X, K)
def corr2d_multi_in_out(X, K):
    return paddle.stack([corr2d_multi_in(X, k) for k in K], 0)
K = paddle.stack((K, K + 1, K + 2), 0)
K.shape
def corr2d_multi_in_out_1x1(X, K):
    c_i, h, w = X.shape
    c_o = K.shape[0]
    X = X.reshape((c_i, h * w))
    K = K.reshape((c_o, c_i))
    Y = paddle.matmul(K, X)
    return Y.reshape((c_o, h, w))
X = paddle.normal(0, 1, (3, 3, 3))
K = paddle.normal(0, 1, (2, 3, 1, 1))
Y1 = corr2d_multi_in_out_1x1(X, K)
Y2 = corr2d_multi_in_out(X, K)
assert float(paddle.abs(Y1 - Y2).sum()) < 1e-6
MXNet: from mxnet import np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l
npx.set_np()
def pool2d(X, pool_size, mode='max'):
    p_h, p_w = pool_size
    Y = np.zeros((X.shape[0] - p_h + 1, X.shape[1] - p_w + 1))
    for i in range(Y.shape[0]):
        for j in range(Y.shape[1]):
            if mode == 'max':
                Y[i, j] = X[i: i + p_h, j: j + p_w].max()
            elif mode == 'avg':
                Y[i, j] = X[i: i + p_h, j: j + p_w].mean()
    return Y
X = np.array([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])
pool2d(X, (2, 2))
X = np.arange(16, dtype=np.float32).reshape((1, 1, 4, 4))
pool2d = nn.MaxPool2D(3)
pool2d(X)
pool2d = nn.MaxPool2D(3, padding=1, strides=2)
pool2d(X)
pool2d = nn.MaxPool2D((2, 3), padding=(0, 1), strides=(2, 3))
pool2d(X)
X = np.concatenate((X, X + 1), 1)
pool2d = nn.MaxPool2D(3, padding=1, strides=2)
pool2d(X)

Paddle: import warnings
from d2l import paddle as d2l
warnings.filterwarnings("ignore")
import paddle
from paddle import nn
def pool2d(X, pool_size, mode='max'):
    p_h, p_w = pool_size
    Y = paddle.zeros((X.shape[0] - p_h + 1, X.shape[1] - p_w + 1))
    for i in range(Y.shape[0]):
        for j in range(Y.shape[1]):
            if mode == 'max':
                Y[i, j] = X[i: i + p_h, j: j + p_w].max()
            elif mode == 'avg':
                Y[i, j] = X[i: i + p_h, j: j + p_w].mean()
    return Y
X = paddle.to_tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])
pool2d(X, (2, 2))
X = paddle.arange(16, dtype="float32").reshape((1, 1, 4, 4))
pool2d = nn.MaxPool2D(3, stride=3)
pool2d(X)
pool2d = nn.MaxPool2D(3, padding=1, stride=2)
pool2d(X)
pool2d = nn.MaxPool2D((2, 3), padding=(0, 1), stride=(2, 3))
pool2d(X)
X = paddle.concat((X, X + 1), 1)
pool2d = paddle.nn.MaxPool2D(3, padding=1, stride=2)
pool2d(X)
MXNet: from mxnet import np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l
npx.set_np()
net = nn.Sequential()
net.add(
    nn.Conv2D(96, kernel_size=11, strides=4, activation='relu'),
    nn.MaxPool2D(pool_size=3, strides=2),
    nn.Conv2D(256, kernel_size=5, padding=2, activation='relu'),
    nn.MaxPool2D(pool_size=3, strides=2),
    nn.Conv2D(384, kernel_size=3, padding=1, activation='relu'),
    nn.Conv2D(384, kernel_size=3, padding=1, activation='relu'),
    nn.Conv2D(256, kernel_size=3, padding=1, activation='relu'),
    nn.MaxPool2D(pool_size=3, strides=2),
    nn.Dense(4096, activation='relu'), nn.Dropout(0.5),
    nn.Dense(4096, activation='relu'), nn.Dropout(0.5),
    nn.Dense(10))
X = np.random.uniform(size=(1, 1, 224, 224))
net.initialize()
for layer in net:
    X = layer(X)
    print(layer.name, 'output shape:	', X.shape)

Paddle: import warnings
from d2l import paddle as d2l
warnings.filterwarnings("ignore")
import paddle
import paddle.nn as nn
net = nn.Sequential(
    nn.Conv2D(1, 96, kernel_size=11, stride=4, padding=1), nn.ReLU(),
    nn.MaxPool2D(kernel_size=3, stride=2),
    nn.Conv2D(96, 256, kernel_size=5, padding=2), nn.ReLU(),
    nn.MaxPool2D(kernel_size=3, stride=2),
    nn.Conv2D(256, 384, kernel_size=3, padding=1), nn.ReLU(),
    nn.Conv2D(384, 384, kernel_size=3, padding=1), nn.ReLU(),
    nn.Conv2D(384, 256, kernel_size=3, padding=1), nn.ReLU(),
    nn.MaxPool2D(kernel_size=3, stride=2), nn.Flatten(),
    nn.Linear(6400, 4096), nn.ReLU(), nn.Dropout(p=0.5),
    nn.Linear(4096, 4096), nn.ReLU(), nn.Dropout(p=0.5),
    nn.Linear(4096, 10))
X = paddle.randn(shape=(1, 1, 224, 224))
for layer in net:
    X=layer(X)
    print(layer.__class__.__name__,'output shape:	',X.shape)
MXNet: from mxnet import np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l
npx.set_np()
def vgg_block(num_convs, num_channels):
    blk = nn.Sequential()
    for _ in range(num_convs):
        blk.add(nn.Conv2D(num_channels, kernel_size=3, padding=1, activation='relu'))
    blk.add(nn.MaxPool2D(pool_size=2, strides=2))
    return blk
def vgg(conv_arch):
    net = nn.Sequential()
    for (num_convs, num_channels) in conv_arch:
        net.add(vgg_block(num_convs, num_channels))
    net.add(nn.Dense(4096, activation='relu'), nn.Dropout(0.5),
            nn.Dense(4096, activation='relu'), nn.Dropout(0.5),
            nn.Dense(10))
    return net
net = vgg(conv_arch)
net.initialize()
X = np.random.uniform(size=(1, 1, 224, 224))
for blk in net:
    X = blk(X)
    print(blk.name, 'output shape:	', X.shape)

Paddle: import warnings
from d2l import paddle as d2l
warnings.filterwarnings("ignore")
import paddle
import paddle.nn as nn
def vgg_block(num_convs, in_channels, out_channels):
    layers = []
    for _ in range(num_convs):
        layers.append(nn.Conv2D(in_channels, out_channels, kernel_size=3, padding=1))
        layers.append(nn.ReLU())
        in_channels = out_channels
    layers.append(nn.MaxPool2D(kernel_size=2, stride=2))
    return nn.Sequential(*layers)
def vgg(conv_arch):
    conv_blks = []
    in_channels = 1
    for (num_convs, out_channels) in conv_arch:
        conv_blks.append(vgg_block(num_convs, in_channels, out_channels))
        in_channels = out_channels
    return nn.Sequential(*conv_blks, nn.Flatten(),
                        nn.Linear(out_channels * 7 * 7, 4096), nn.ReLU(),
                        nn.Dropout(0.5), nn.Linear(4096, 4096), nn.ReLU(),
                        nn.Dropout(0.5), nn.Linear(4096, 10))
net = vgg(conv_arch)
X = paddle.randn(shape=(1, 1, 224, 224))
for blk in net:
    X = blk(X)
    print(blk.__class__.__name__,'output shape:	',X.shape)
MXNet: from mxnet import np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l
npx.set_np()
def nin_block(num_channels, kernel_size, strides, padding):
    blk = nn.Sequential()
    blk.add(nn.Conv2D(num_channels, kernel_size, strides, padding, activation='relu'),
            nn.Conv2D(num_channels, kernel_size=1, activation='relu'),
            nn.Conv2D(num_channels, kernel_size=1, activation='relu'))
    return blk
net = nn.Sequential()
net.add(nin_block(96, kernel_size=11, strides=4, padding=0),
        nn.MaxPool2D(pool_size=3, strides=2),
        nin_block(256, kernel_size=5, strides=1, padding=2),
        nn.MaxPool2D(pool_size=3, strides=2),
        nin_block(384, kernel_size=3, strides=1, padding=1),
        nn.MaxPool2D(pool_size=3, strides=2),
        nn.Dropout(0.5),
        nin_block(10, kernel_size=3, strides=1, padding=1),
        nn.GlobalAvgPool2D(),
        nn.Flatten())
X = np.random.uniform(size=(1, 1, 224, 224))
net.initialize()
for layer in net:
    X = layer(X)
    print(layer.name, 'output shape:	', X.shape)

Paddle: import warnings
from d2l import paddle as d2l
warnings.filterwarnings("ignore")
import paddle
import paddle.nn as nn
def nin_block(in_channels, out_channels, kernel_size, strides, padding):
    return nn.Sequential(
        nn.Conv2D(in_channels, out_channels, kernel_size, strides, padding),
        nn.ReLU(),
        nn.Conv2D(out_channels, out_channels, kernel_size=1),
        nn.ReLU(),
        nn.Conv2D(out_channels, out_channels, kernel_size=1),
        nn.ReLU())
net = nn.Sequential(
    nin_block(1, 96, kernel_size=11, strides=4, padding=0),
    nn.MaxPool2D(3, stride=2),
    nin_block(96, 256, kernel_size=5, strides=1, padding=2),
    nn.MaxPool2D(3, stride=2),
    nin_block(256, 384, kernel_size=3, strides=1, padding=1),
    nn.MaxPool2D(3, stride=2), nn.Dropout(0.5),
    nin_block(384, 10, kernel_size=3, strides=1, padding=1),
    nn.AdaptiveAvgPool2D((1, 1)),
    nn.Flatten())
X = paddle.rand(shape=(1, 1, 224, 224))
for layer in net:
    X = layer(X)
    print(layer.__class__.__name__,'output shape:	', X.shape)
MXNet: import collections
import re
from d2l import mxnet as d2l

Paddle: import collections
import re
from d2l import paddle as d2l
MXNet: import random
from mxnet import np, npx
from d2l import mxnet as d2l
npx.set_np()
tokens = d2l.tokenize(d2l.read_time_machine())
corpus = [token for line in tokens for token in line]
vocab = d2l.Vocab(corpus)
vocab.token_freqs[:10]
def seq_data_iter_random(corpus, batch_size, num_steps):
    corpus = corpus[random.randint(0, num_steps - 1):]
    num_subseqs = (len(corpus) - 1) // num_steps
    initial_indices = list(range(0, num_subseqs * num_steps, num_steps))
    random.shuffle(initial_indices)
    def data(pos):
        return corpus[pos: pos + num_steps]
    num_batches = num_subseqs // batch_size
    for i in range(0, batch_size * num_batches, batch_size):
        initial_indices_per_batch = initial_indices[i: i + batch_size]
        X = [data(j) for j in initial_indices_per_batch]
        Y = [data(j + 1) for j in initial_indices_per_batch]
        yield np.array(X), np.array(Y)
def seq_data_iter_sequential(corpus, batch_size, num_steps):
    offset = random.randint(0, num_steps)
    num_tokens = ((len(corpus) - offset - 1) // batch_size) * batch_size
    Xs = np.array(corpus[offset: offset + num_tokens])
    Ys = np.array(corpus[offset + 1: offset + 1 + num_tokens])
    Xs, Ys = Xs.reshape(batch_size, -1), Ys.reshape(batch_size, -1)
    num_batches = Xs.shape[1] // num_steps
    for i in range(0, num_steps * num_batches, num_steps):
        X = Xs[:, i: i + num_steps]
        Y = Ys[:, i: i + num_steps]
        yield X, Y

Paddle: import warnings
from d2l import paddle as d2l
warnings.filterwarnings("ignore")
import random
import paddle
tokens = d2l.tokenize(d2l.read_time_machine())
corpus = [token for line in tokens for token in line]
vocab = d2l.Vocab(corpus)
vocab.token_freqs[:10]
def seq_data_iter_random(corpus, batch_size, num_steps):
    corpus = corpus[random.randint(0, num_steps - 1):]
    num_subseqs = (len(corpus) - 1) // num_steps
    initial_indices = list(range(0, num_subseqs * num_steps, num_steps))
    random.shuffle(initial_indices)
    def data(pos):
        return corpus[pos: pos + num_steps]
    num_batches = num_subseqs // batch_size
    for i in range(0, batch_size * num_batches, batch_size):
        initial_indices_per_batch = initial_indices[i: i + batch_size]
        X = [data(j) for j in initial_indices_per_batch]
        Y = [data(j + 1) for j in initial_indices_per_batch]
        yield paddle.to_tensor(X), paddle.to_tensor(Y)
def seq_data_iter_sequential(corpus, batch_size, num_steps):
    offset = random.randint(0, num_steps)
    num_tokens = ((len(corpus) - offset - 1) // batch_size) * batch_size
    Xs = paddle.to_tensor(corpus[offset: offset + num_tokens])
    Ys = paddle.to_tensor(corpus[offset + 1: offset + 1 + num_tokens])
    Xs, Ys = Xs.reshape((batch_size, -1)), Ys.reshape((batch_size, -1))
    num_batches = Xs.shape[1] // num_steps
    for i in range(0, num_steps * num_batches, num_steps):
        X = Xs[:, i: i + num_steps]
        Y = Ys[:, i: i + num_steps]
        yield X, Y
MXNet: from mxnet import np, npx
from d2l import mxnet as d2l
npx.set_np()
X, W_xh = np.random.normal(0, 1, (3, 1)), np.random.normal(0, 1, (1, 4))
H, W_hh = np.random.normal(0, 1, (3, 4)), np.random.normal(0, 1, (4, 4))
np.dot(X, W_xh) + np.dot(H, W_hh)
np.dot(np.concatenate((X, H), 1), np.concatenate((W_xh, W_hh), 0))

Paddle: import warnings
from d2l import paddle as d2l
warnings.filterwarnings("ignore")
import paddle
X, W_xh = paddle.normal(0, 1, (3, 1)), paddle.normal(0, 1, (1, 4))
H, W_hh = paddle.normal(0, 1, (3, 4)), paddle.normal(0, 1, (4, 4))
paddle.matmul(X, W_xh) + paddle.matmul(H, W_hh)
paddle.matmul(paddle.concat((X, H), 1), paddle.concat((W_xh, W_hh), 0))
MXNet: import os
from mxnet import np, npx
from d2l import mxnet as d2l
npx.set_np()
def build_array_nmt(lines, vocab, num_steps):
    lines = [vocab[l] for l in lines]
    lines = [l + [vocab['<eos>']] for l in lines]
    array = np.array([truncate_pad(l, num_steps, vocab['<pad>']) for l in lines])
    valid_len = (array != vocab['<pad>']).astype(np.int32).sum(1)
    return array, valid_len
train_iter, src_vocab, tgt_vocab = load_data_nmt(batch_size=2, num_steps=8)
for X, X_valid_len, Y, Y_valid_len in train_iter:
    print('X:', X.astype(np.int32))
    print('Valid length of X:', X_valid_len)
    print('Y:', Y.astype(np.int32))
    print('Valid length of Y:', Y_valid_len)
    break

Paddle: import warnings
from d2l import paddle as d2l
warnings.filterwarnings("ignore")
import os
import paddle
def build_array_nmt(lines, vocab, num_steps):
    lines = [vocab[l] for l in lines]
    lines = [l + [vocab['<eos>']] for l in lines]
    array = paddle.to_tensor([truncate_pad(l, num_steps, vocab['<pad>']) for l in lines])
    valid_len = (array != vocab['<pad>']).astype(paddle.int32).sum(1)
    return array, valid_len
train_iter, src_vocab, tgt_vocab = load_data_nmt(batch_size=2, num_steps=8)
for X, X_valid_len, Y, Y_valid_len in train_iter:
    print('X:', X.astype(paddle.int32))
    print('Valid length of X:', X_valid_len)
    print('Y:', Y..astype(paddle.int32))
    print('Valid length of Y:', Y_valid_len)
    break
PyTorch: x = torch.arange(12)
x.numel()
torch.zeros((2, 3, 4))
torch.ones((2, 3, 4))
torch.randn(3, 4)
torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y
torch.exp(x)
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
torch.cat((X, Y), dim=0), torch.cat((X, Y), dim=1)
a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
Z = torch.zeros_like(Y)
Z[:] = X + Y
A = X.numpy()
B = torch.tensor(A)
a = torch.tensor([3.5])
print(a, a.item(), float(a), int(a))

MXNet: x = np.arange(12)
x.size
np.zeros((2, 3, 4))
np.ones((2, 3, 4))
np.random.normal(0, 1, size=(3, 4))
np.array([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
x = np.array([1, 2, 4, 8])
y = np.array([2, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y
np.exp(x)
X = np.arange(12).reshape(3, 4)
Y = np.array([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
np.concatenate([X, Y], axis=0), np.concatenate([X, Y], axis=1)
a = np.arange(3).reshape(3, 1)
b = np.arange(2).reshape(1, 2)
Z = np.zeros_like(Y)
Z[:] = X + Y
A = X.asnumpy()
B = np.array(A)
a = np.array([3.5])
print(a, a.item(), float(a), int(a))
PyTorch: import torch
X, y = torch.tensor(inputs.values), torch.tensor(outputs.values)

MXNet: from mxnet import np
X, y = np.array(inputs.values), np.array(outputs.values)
PyTorch: import torch
x = torch.tensor(3.0)
y = torch.tensor(2.0)
print(x + y, x * y, x / y, x**y)
x = torch.arange(4)
A = torch.arange(20).reshape(5, 4)
B = torch.tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]])
X = torch.arange(24).reshape(2, 3, 4)
A = torch.arange(20, dtype=torch.float32).reshape(5, 4)
B = A.clone()
print(A, A + B)
a = 2
X = torch.arange(24).reshape(2, 3, 4)
print(a + X, (a * X).shape)
x = torch.arange(4, dtype=torch.float32)
print(x, x.sum())
A.mean()
A.sum() / A.numel()
y = torch.ones(4, dtype = torch.float32)
print(torch.dot(x, y))
torch.sum(x * y)
A.shape, x.shape, torch.mv(A, x)
B = torch.ones(4, 3)
torch.mm(A, B)
u = torch.tensor([3.0, -4.0])
torch.norm(u)
torch.abs(u).sum()
torch.norm(torch.ones((4, 9)))

MXNet: from mxnet import np, npx
npx.set_np()
x = np.array(3.0)
y = np.array(2.0)
print(x + y, x * y, x / y, x**y)
x = np.arange(4)
A = np.arange(20).reshape(5, 4)
B = np.array([[1, 2, 3], [2, 0, 4], [3, 4, 5]])
X = np.arange(24).reshape(2, 3, 4)
A = np.arange(20).reshape(5, 4)
B = A.copy()
print(A, A + B)
a = 2
X = np.arange(24).reshape(2, 3, 4)
print(a + X, (a * X).shape)
x = np.arange(4)
print(x, x.sum())
A.mean()
A.sum() / A.size
y = np.ones(4)
print(np.dot(x, y))
np.sum(x * y)
A.shape, x.shape, np.dot(A, x)
B = np.ones(shape=(4, 3))
np.dot(A, B)
u = np.array([3, -4])
np.linalg.norm(u)
np.abs(u).sum()
np.linalg.norm(np.ones((4, 9)))
PyTorch: %matplotlib inline
import numpy as np
from matplotlib_inline import backend_inline
from d2l import torch as d2l
def f(x):
    return 3 * x ** 2 - 4 * x

MXNet: %matplotlib inline
from matplotlib_inline import backend_inline
from mxnet import np, npx
from d2l import mxnet as d2l
npx.set_np()
def f(x):
    return 3 * x ** 2 - 4 * x