DocsData & AITensor Computation & Neural Networks
Data & AI

Tensor Computation & Neural Networks

N-dimensional array tensors, automatic differentiation, neural network layers, and optimizers.

NextViper AI & Tensor Framework

The NextViper tensor and ai packages provide hardware-accelerated tensor computation with reverse-mode automatic differentiation and modular deep learning layers.


1. Tensor Creation & Operations

nextviper
import tensor

// Multi-dimensional tensor on CPU or GPU
let a = tensor.matrix([[1.0, 2.0], [3.0, 4.0]], device: "gpu")
let b = tensor.matrix([[5.0, 6.0], [7.0, 8.0]], device: "gpu")

// Matrix Multiplication (accelerated with Vulkan / SIMD)
let c = a.matmul(b)
print("Result C:
", c)

2. Automatic Differentiation (Autograd)

nextviper
import tensor

let x = tensor.scalar(3.0, requires_grad: true)
let y = (x * x * 2.0) + (x * 5.0) + 1.0

// Compute dy/dx
y.backward()
print("Gradient dy/dx at x=3:", x.grad) // 4 * 3 + 5 = 17.0

3. Training a Deep Learning Model

nextviper
import tensor
import ai

// Define Sequential Architecture
let model = ai.Sequential([
    ai.Dense(input_dim: 128, output_dim: 64, activation: "relu"),
    ai.Dropout(rate: 0.2),
    ai.Dense(input_dim: 64, output_dim: 10, activation: "softmax")
]).to("gpu")

let optimizer = ai.Adam(model.parameters(), lr: 0.001)

// Forward & Backward Step
for epoch in 0..100 {
    let predictions = model.forward(x_train)
    let loss = ai.cross_entropy_loss(predictions, y_train)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if epoch % 10 == 0 {
        print("Epoch", epoch, "| Loss:", loss.item())
    }
}