Tensor and numerical foundations · Easy

Batched Linear Projection

Problem 3 of 50 · Python and NumPy

Problem

Apply a shared linear projection to every token in a batch. Compute y[b,t,o] = sum_i x[b,t,i] * weight[i,o] + bias[o]. Return shape B × T × O. The weight layout is input-feature first.

def linear_projection(x, weight, bias):

Constraints

  • 1 ≤ B,T,I,O ≤ 8; x has shape B × T × I, weight I × O, bias O.
  • Finite inputs have magnitude at most 100.
  • Inputs satisfy these constraints; invalid-input handling is not graded. Use only Python standard library and NumPy.

Examples

Example 1

Arguments: [
  [
    [
      [
        1,
        2
      ]
    ]
  ],
  [
    [
      1
    ],
    [
      3
    ]
  ],
  [
    1
  ]
]
Expected result: [
  [
    [
      8
    ]
  ]
]

1×1 + 2×3 + 1 = 8.

Example 2

Arguments: [
  [
    [
      [
        1,
        0
      ]
    ],
    [
      [
        0,
        1
      ]
    ]
  ],
  [
    [
      1,
      2
    ],
    [
      3,
      4
    ]
  ],
  [
    0,
    1
  ]
]
Expected result: [
  [
    [
      1,
      3
    ]
  ],
  [
    [
      3,
      5
    ]
  ]
]

Each one-hot input selects a weight row before adding [0,1].

Sign in to solve this problem

Browse all coding problems · Learn the foundations