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
Transformer Block in PyTorch
00:00
5 left

Transformer Block in PyTorch

HardPython

Problem

Implement a transformer block from scratch in PyTorch.

Implement the forward pass for a batch-first transformer block with multi-head self-attention, scaled dot-product attention, residual connections, layer normalization, and a two-layer feed-forward network. For grading, represent x as a nested Python list with shape [batch_size][sequence_length][d_model]; return a nested list with the same shape. Use dropout = 0 for deterministic execution. The reference implementation uses identity projections to keep the standard-library test harness deterministic.

Constraints

  • 1 <= batch_size <= 64
  • 1 <= sequence_length <= 512
  • 1 <= d_model <= 1024
  • d_model is divisible by num_heads
  • 1 <= num_heads <= d_model
  • 1 <= d_ff
  • dropout = 0 for deterministic grading
  • x contains finite floating-point values

Function Signature

def transformer_block(x, d_model, num_heads, d_ff, dropout):
Interviewer

Your question is Transformer Block in PyTorch. 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.