Bird
Raised Fist0
PyTorchml~20 mins

Hugging Face integration basics in PyTorch - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Hugging Face Integration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Hugging Face tokenizer usage
What is the output of the following code snippet that uses a Hugging Face tokenizer to tokenize a sentence?
PyTorch
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
inputs = tokenizer('Hello world!', return_tensors='pt')
print(inputs['input_ids'].tolist())
A[[7592, 2088, 999]]
B[[101, 7592, 2088, 999, 102]]
C[[101, 7592, 2088, 999]]
D[[101, 7592, 2088, 102]]
Attempts:
2 left
💡 Hint
Remember that BERT tokenizers add special tokens at the start and end.
❓ Model Choice
intermediate
2:00remaining
Choosing the correct Hugging Face model for text classification
You want to perform sentiment analysis on movie reviews using Hugging Face. Which model is best suited for this task?
Adistilbert-base-uncased-finetuned-sst-2-english
Bbert-base-uncased
Croberta-base
Dgpt2
Attempts:
2 left
💡 Hint
Look for a model fine-tuned for sentiment analysis.
❓ Hyperparameter
advanced
2:00remaining
Effect of batch size on Hugging Face model training
During fine-tuning a Hugging Face transformer model, what is the main effect of increasing the batch size?
AIt decreases the learning rate automatically.
BIt increases the model's ability to generalize by adding noise to gradients.
CIt always improves model accuracy regardless of dataset size.
DIt reduces training time per epoch but may require more memory.
Attempts:
2 left
💡 Hint
Think about computational resources and speed.
❓ Metrics
advanced
2:00remaining
Correct metric for evaluating Hugging Face text generation
Which metric is most appropriate to evaluate the quality of text generated by a Hugging Face language model?
ABLEU score
BF1 score
CAccuracy
DMean Squared Error
Attempts:
2 left
💡 Hint
Consider metrics used in machine translation and text generation.
🔧 Debug
expert
2:00remaining
Identifying error in Hugging Face model loading code
What error will this code raise when trying to load a Hugging Face model and tokenizer?
PyTorch
from transformers import AutoModel, AutoTokenizer

model = AutoModel.from_pretrained('bert-base-uncased')
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
inputs = tokenizer('Test input', return_tensors='pt')
outputs = model(inputs)
ARuntimeError: CUDA out of memory
BValueError: Invalid model name
CTypeError: forward() missing 1 required positional argument: 'input_ids'
DNo error, code runs successfully
Attempts:
2 left
💡 Hint
Check how the model expects inputs.

Practice

(1/5)
1. What is the main purpose of the AutoTokenizer class in Hugging Face integration with PyTorch?
easy
A. To visualize model predictions
B. To convert raw text into tokens that the model can understand
C. To train a new language model from scratch
D. To save the model weights to disk

Solution

  1. Step 1: Understand the role of tokenization

    Tokenization breaks down raw text into smaller pieces called tokens, which models use as input.
  2. Step 2: Identify what AutoTokenizer does

    AutoTokenizer automatically loads the correct tokenizer for a given pretrained model to convert text into tokens.
  3. Final Answer:

    To convert raw text into tokens that the model can understand -> Option B
  4. Quick Check:

    AutoTokenizer = text to tokens [OK]
Hint: Tokenizer = text to tokens for model input [OK]
Common Mistakes:
  • Confusing tokenizer with model training
  • Thinking tokenizer saves model weights
  • Assuming tokenizer visualizes outputs
2. Which of the following is the correct way to load a pretrained model using Hugging Face's AutoModel in PyTorch?
easy
A. model = AutoModel.from_pretrained('bert-base-uncased')
B. model = AutoModel.load('bert-base-uncased')
C. model = AutoModel('bert-base-uncased')
D. model = AutoModel.pretrained('bert-base-uncased')

Solution

  1. Step 1: Recall the correct method to load pretrained models

    Hugging Face uses the from_pretrained method to load pretrained weights and configuration.
  2. Step 2: Match the correct syntax

    The correct syntax is AutoModel.from_pretrained('model_name').
  3. Final Answer:

    model = AutoModel.from_pretrained('bert-base-uncased') -> Option A
  4. Quick Check:

    Load model with from_pretrained() [OK]
Hint: Use from_pretrained() to load models [OK]
Common Mistakes:
  • Using .load() instead of .from_pretrained()
  • Calling AutoModel like a function
  • Using non-existent .pretrained() method
3. Given the following code snippet, what will be the shape of outputs.last_hidden_state?
from transformers import AutoTokenizer, AutoModel
import torch

tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
model = AutoModel.from_pretrained('bert-base-uncased')

inputs = tokenizer('Hello world!', return_tensors='pt')
outputs = model(**inputs)
medium
A. [2, 768]
B. [1, 768]
C. [1, 5, 768]
D. [768, 2]

Solution

  1. Step 1: Understand the tokenizer output

    The tokenizer returns input IDs with shape [batch_size, sequence_length]. Here batch_size=1 and sequence_length=5 (tokens: [CLS], 'hello', 'world', '!', [SEP]).
  2. Step 2: Understand model output shape

    The model outputs last_hidden_state with shape [batch_size, sequence_length, hidden_size]. For BERT base, hidden_size=768.
  3. Final Answer:

    [1, 5, 768] -> Option C
  4. Quick Check:

    Output shape = [batch, tokens, features] = [1, 5, 768] [OK]
Hint: Output shape = batch x tokens x hidden size [OK]
Common Mistakes:
  • Confusing sequence length with batch size
  • Ignoring hidden size dimension
  • Assuming output shape is 2D instead of 3D
4. Identify the error in this Hugging Face PyTorch code snippet:
from transformers import AutoTokenizer, AutoModel

tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
model = AutoModel.from_pretrained('bert-base-uncased')

inputs = tokenizer('Test input', return_tensors='pt')
outputs = model(inputs)
print(outputs)
medium
A. Missing .to(device) to move inputs to GPU
B. AutoModel cannot be used with BERT models
C. Tokenizer should use return_tensors='tf' instead of 'pt'
D. Model should be called with unpacked inputs: model(**inputs)

Solution

  1. Step 1: Check how model is called

    The model expects keyword arguments, so inputs must be unpacked with ** to pass input_ids and attention_mask correctly.
  2. Step 2: Identify the fix

    Change model(inputs) to model(**inputs) to avoid errors.
  3. Final Answer:

    Model should be called with unpacked inputs: model(**inputs) -> Option D
  4. Quick Check:

    Use **inputs when calling model [OK]
Hint: Call model with model(**inputs) not model(inputs) [OK]
Common Mistakes:
  • Passing inputs as a single dict argument
  • Confusing PyTorch and TensorFlow tensor types
  • Thinking AutoModel can't load BERT
5. You want to classify text into positive or negative sentiment using a Hugging Face model in PyTorch. After tokenizing and running the model, which step correctly converts raw model outputs into class probabilities?
hard
A. Apply torch.softmax on the model's logits output
B. Use torch.argmax directly on tokenized inputs
C. Call model.eval() to get probabilities
D. Normalize input tokens before feeding to the model

Solution

  1. Step 1: Understand model output for classification

    Models output raw scores called logits for each class, which are not probabilities.
  2. Step 2: Convert logits to probabilities

    Applying torch.softmax on logits converts them into probabilities summing to 1.
  3. Final Answer:

    Apply torch.softmax on the model's logits output -> Option A
  4. Quick Check:

    Softmax = logits to probabilities [OK]
Hint: Use softmax on logits to get probabilities [OK]
Common Mistakes:
  • Using argmax on inputs instead of outputs
  • Confusing model.eval() with probability conversion
  • Normalizing inputs instead of outputs
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard