Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Implement Multi-Head Attention
00:00
5 left

Implement Multi-Head Attention

HardPython

Problem

Implement Multi-Head Self-Attention (MHA) from scratch in PyTorch, ensuring your implementation supports batching and causal masking.

Accept x with shape [batch, sequence, model_dim] and projection matrices with shape [model_dim, model_dim]. Return the projected attention output as a nested list with the same shape as x; inputs are provided as JSON-compatible lists and must be converted to PyTorch tensors internally.

Use scaled dot-product attention, split the model dimension across num_heads, apply the upper-triangular future-token mask when causal is true, concatenate heads, and apply w_o. Assume model_dim is divisible by num_heads.

Constraints

  • x has shape [batch_size, sequence_length, model_dim]
  • Each projection matrix has shape [model_dim, model_dim]
  • 1 <= batch_size <= 128
  • 1 <= sequence_length <= 2048
  • 1 <= num_heads <= model_dim
  • model_dim is divisible by num_heads
  • causal is a boolean

Function Signature

def mha(x, w_q, w_k, w_v, w_o, num_heads, causal):
Interviewer

Your question is Implement Multi-Head Attention. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
Sign up free to run your codeLog inLn 2
Run your code to see test output here.