Bird
Raised Fist0

Gradient Check Gone Wrong

CODINGadvancedInterview freq: high
Choose your preparation mode6 modes available
🐛
The Gradient Check Dilemma
Started after the latest deployment, ongoing for 3 days.

A neural network model for image classification, deployed to process 500K images daily.

Symptom
The model's training loss is increasing instead of decreasing, and the accuracy is dropping over epochs.
📡
Signals
metric
Training loss over epochs
Loss increased from 0.5 to 1.2 over 10 epochs.
metric
Training accuracy over epochs
Accuracy dropped from 85% to 60% over 10 epochs.
log
Gradient check logs
Numerical gradient differs significantly from analytical gradient.
code
Gradient computation code
Recent changes in the gradient computation logic.
distribution
Distribution of gradient values
Gradients have a high variance, with some values being NaN.
🔬
Hypotheses
Numerical gradient computation is incorrect.
Gradient check logsDistribution of gradient values
Verify: Check the numerical gradient computation for errors in finite difference approximation.
def numerical_gradient(f, x):
    h = 1e-5
    grad = np.zeros_like(x)
    for i in range(x.size):
        x[i] += h
        fxh1 = f(x)
        x[i] -= 2 * h
        fxh2 = f(x)
        grad[i] = (fxh1 - fxh2) / (2 * h)
        x[i] += h
    return grad
Analytical gradient computation has a bug.
Gradient check logsCode
Verify: Review the analytical gradient computation logic for recent changes.
def analytical_gradient(x):
    # Implement the analytical gradient computation logic
    pass
🎯
Root Cause
Numerical gradient computation was using an incorrect step size, leading to inaccurate gradient estimates.

A recent code change inadvertently altered the step size used in the numerical gradient computation.

🔧
Fix Strategy
ImmediateRevert to the previous stable version of the gradient computation code.
Short-termCorrect the step size in the numerical gradient computation to ensure accurate gradient checking.
Long-termImplement automated tests for gradient checking to catch such errors before deployment.
🐍
Python Fix
Python
def numerical_gradient(f, x):
    h = 1e-5  # Correct step size
    grad = np.zeros_like(x)
    for i in range(x.size):
        x[i] += h
        fxh1 = f(x)
        x[i] -= 2 * h
        fxh2 = f(x)
        grad[i] = (fxh1 - fxh2) / (2 * h)
        x[i] += h
    return grad
✗
Common Wrong Diagnoses
▼ Show
The model architecture is flawed.
Why candidates think this: The symptoms of increasing loss and decreasing accuracy suggest a fundamental issue with the model.
Why wrong: The gradient check logs specifically indicate a problem with gradient computation, not the model architecture.
The dataset has changed unexpectedly.
Why candidates think this: A sudden drop in performance could be due to data distribution changes.
Why wrong: The issue persisted even with the same dataset, and the gradient check logs pointed to computation errors.
📊
Monitoring to Add
  • Automated gradient check validation in CI/CD pipeline.
  • Alerts for significant discrepancies between numerical and analytical gradients.
  • Monitoring of gradient distribution for NaN values.
📋
Process Change

Introduce code reviews specifically for numerical methods and gradient computations.

🏗️
Architectural Change

Develop a robust testing framework for numerical methods used in model training.

💡
Key Insight
Accurate gradient checking is crucial for reliable model training, and even small errors in numerical methods can lead to significant performance issues.

Practice

(1/5)
1. What does the following Python code output when applied to an image array img?
import numpy as np

def flip_image(img):
    return np.flip(img, axis=1)

img = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
flipped_img = flip_image(img)
print(flipped_img)
easy
A. [[3, 2, 1], [6, 5, 4], [9, 8, 7]]
B. [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
C. [[7, 8, 9], [4, 5, 6], [1, 2, 3]]
D. [[9, 8, 7], [6, 5, 4], [3, 2, 1]]

Solution

  1. Step 1: Understand the flip operation

    The np.flip function flips the array along the specified axis. Here, axis=1 means flipping horizontally.
  2. Step 2: Apply the flip to the array

    Flipping horizontally changes the order of elements in each row.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Horizontal flip reverses row elements. [OK]
Hint: Horizontal flip reverses row elements. [OK]
Common Mistakes:
2. What is the time complexity of calculating the mean Average Precision (mAP) for a single image with N predicted bounding boxes and M ground truth boxes?
easy
A. O(N + M)
B. O(N^2)
C. O(N * M)
D. O(M^2)

Solution

  1. Step 1: Understand the Process

    For each predicted box, IoU is calculated with each ground truth box, leading to N * M comparisons.
  2. Step 2: Determine Complexity

    Each comparison is constant time, so the overall complexity is O(N * M).
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    IoU comparisons drive complexity [OK]
Hint: IoU comparisons drive complexity [OK]
Common Mistakes:
3. What does the following Python code snippet output when implementing sinusoidal positional encoding?
import numpy as np

def positional_encoding(position, d_model):
    angle_rads = np.arange(position)[:, np.newaxis] / np.power(10000, (2 * (np.arange(d_model)[np.newaxis, :] // 2)) / np.float32(d_model))
    angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])
    angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])
    return angle_rads

pe = positional_encoding(4, 4)
print(pe)
easy
A. A 4x4 matrix with alternating sine and cosine values
B. A 4x4 matrix with random values
C. A 4x4 identity matrix
D. A 4x4 matrix with all zeros

Solution

  1. Step 1: Understand the code logic

    The code generates a matrix where each row corresponds to a position and each column to a dimension, filled with sinusoidal values.
  2. Step 2: Eliminate wrong options

    A 4x4 matrix with all zeros is incorrect because the matrix is not filled with zeros. A 4x4 identity matrix is incorrect because the matrix is not an identity matrix. A 4x4 matrix with random values is incorrect because the values are not random but deterministic sinusoidal values.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sinusoidal encoding alternates sine/cosine. [OK]
Hint: Sinusoidal encoding alternates sine/cosine. [OK]
Common Mistakes:
4. What does the following Python code output when computing the ROC curve?
from sklearn.metrics import roc_curve
import numpy as np

y_true = np.array([0, 0, 1, 1])
y_scores = np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr, thresholds = roc_curve(y_true, y_scores)
print(fpr, tpr, thresholds)
easy
A. array([0. , 0.5, 0.5, 1. ]), array([0. , 0. , 1. , 1. ]), array([1.8, 0.8, 0.4, 0.1])
B. array([0. , 0. , 0.5, 1. ]), array([0. , 0.5, 1. , 1. ]), array([0.8, 0.4, 0.35, 0.1])
C. array([0. , 0.5, 1. ]), array([0. , 0.5, 1. ]), array([0.8, 0.35, 0.1])
D. array([0. , 0.5, 1. ]), array([0. , 1. , 1. ]), array([0.8, 0.35, 0.1])

Solution

  1. Step 1: Understand ROC curve output

    The ROC curve function returns false positive rates (fpr), true positive rates (tpr), and thresholds.
  2. Step 2: Analyze the code

    Given the scores and true labels, the ROC curve is calculated correctly, resulting in fpr, tpr, and thresholds as in array([0. , 0.5, 1. ]), array([0. , 0.5, 1. ]), array([0.8, 0.35, 0.1]).
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    ROC curve outputs fpr, tpr, thresholds [OK]
Hint: ROC curve outputs fpr, tpr, thresholds [OK]
Common Mistakes:
5. A Gaussian Naive Bayes model is giving poor performance on a dataset. Which of the following is the most likely cause?
medium
A. The model has too many parameters.
B. The features are not normally distributed.
C. The dataset is too small.
D. The features are highly correlated.

Solution

  1. Step 1: Identify Gaussian Naive Bayes assumptions

    Gaussian Naive Bayes assumes that features are normally distributed.
  2. Step 2: Evaluate each option

    The features are not normally distributed. is correct because non-normal distribution violates the model's assumptions. The model has too many parameters. is incorrect as GaussianNB is simple. The dataset is too small. is less likely as small datasets affect all models. The features are highly correlated. is incorrect as GaussianNB can handle correlated features.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    GaussianNB assumes normal distribution. [OK]
Hint: GaussianNB assumes normal distribution. [OK]
Common Mistakes:
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