debug:tensorflow
Debug TensorFlow and Keras issues systematically. This skill helps diagnose and resolve machine learning problems including tensor shape mismatches, GPU/CUDA detection failures, out-of-memory errors, NaN/Inf values in loss functions, vanishing/exploding gradients, SavedModel loading errors, and data pipeline bottlenecks. Provides tf.debugging assertions, TensorBoard profiling, eager execution debugging, and version compatibility guidance.
What this skill does
# TensorFlow Debugging Guide
This skill provides a systematic approach to debugging TensorFlow applications, covering common error patterns, debugging tools, and resolution strategies.
## Common Error Patterns
### 1. Shape Mismatch Errors
**Symptoms:**
- `InvalidArgumentError: Incompatible shapes`
- `ValueError: Shapes (X,) and (Y,) are incompatible`
- Matrix multiplication failures
**Diagnostic Steps:**
```python
# Print shapes at key points
print(f"Input shape: {x.shape}")
print(f"Expected shape: {model.input_shape}")
# Use tf.debugging for assertions
tf.debugging.assert_shapes([
(x, ('batch', 'features')),
(y, ('batch', 'classes'))
])
# Enable eager execution for immediate shape inspection
tf.config.run_functions_eagerly(True)
```
**Common Causes:**
- Batch dimension mismatch (missing or extra dimension)
- Incorrect reshape operations
- Mismatched layer input/output dimensions
- Broadcasting issues with incompatible shapes
**Solutions:**
```python
# Expand dimensions if needed
x = tf.expand_dims(x, axis=0) # Add batch dimension
# Reshape explicitly
x = tf.reshape(x, [-1, height, width, channels])
# Use tf.ensure_shape for runtime validation
x = tf.ensure_shape(x, [None, 224, 224, 3])
```
### 2. OOM (Out of Memory) Errors
**Symptoms:**
- `ResourceExhaustedError: OOM when allocating tensor`
- `CUDA_ERROR_OUT_OF_MEMORY`
- Training crashes after a few epochs
**Diagnostic Steps:**
```python
# Check GPU memory usage
gpus = tf.config.list_physical_devices('GPU')
if gpus:
for gpu in gpus:
details = tf.config.experimental.get_device_details(gpu)
print(f"GPU: {gpu.name}, Details: {details}")
# Monitor memory during training
tf.debugging.experimental.enable_dump_debug_info(
'/tmp/tfdbg2_logdir',
tensor_debug_mode='FULL_HEALTH',
circular_buffer_size=1000
)
```
**Solutions:**
```python
# Enable memory growth (prevent TF from allocating all GPU memory)
gpus = tf.config.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
# Limit GPU memory
tf.config.set_logical_device_configuration(
gpus[0],
[tf.config.LogicalDeviceConfiguration(memory_limit=4096)] # 4GB
)
# Reduce batch size
BATCH_SIZE = 16 # Try smaller values
# Use gradient checkpointing for large models
# (recompute activations during backward pass)
# Clear session between runs
tf.keras.backend.clear_session()
# Use mixed precision training
tf.keras.mixed_precision.set_global_policy('mixed_float16')
```
### 3. NaN/Inf in Loss
**Symptoms:**
- Loss becomes `nan` or `inf` during training
- Model predictions are all NaN
- Gradient norm explodes
**Diagnostic Steps:**
```python
# Enable numeric checking
tf.debugging.enable_check_numerics()
# Check for NaN in tensors
tf.debugging.check_numerics(tensor, "Tensor contains NaN or Inf")
# Use TensorBoard Debugger V2
tf.debugging.experimental.enable_dump_debug_info(
logdir='/tmp/tfdbg2_logdir',
tensor_debug_mode='FULL_HEALTH',
circular_buffer_size=1000
)
```
**Common Causes:**
- Learning rate too high
- Exploding gradients
- Log of zero or negative numbers
- Division by zero
- Incorrect loss function for data range
**Solutions:**
```python
# Reduce learning rate
optimizer = tf.keras.optimizers.Adam(learning_rate=1e-5)
# Add gradient clipping
optimizer = tf.keras.optimizers.Adam(clipnorm=1.0)
# or
optimizer = tf.keras.optimizers.Adam(clipvalue=0.5)
# Use numerically stable operations
# Instead of: tf.math.log(x)
tf.math.log(x + 1e-7) # Add epsilon
# Instead of: x / y
tf.math.divide_no_nan(x, y)
# Add batch normalization
model.add(tf.keras.layers.BatchNormalization())
# Check data for NaN before training
assert not tf.reduce_any(tf.math.is_nan(train_data)).numpy()
```
### 4. Gradient Issues
**Symptoms:**
- Vanishing gradients (weights not updating)
- Exploding gradients (loss becomes NaN)
- Training stalls, loss doesn't decrease
**Diagnostic Steps:**
```python
# Inspect gradients with GradientTape
with tf.GradientTape() as tape:
predictions = model(x, training=True)
loss = loss_fn(y, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
for var, grad in zip(model.trainable_variables, gradients):
if grad is not None:
print(f"{var.name}: grad_norm={tf.norm(grad).numpy():.6f}")
else:
print(f"{var.name}: NO GRADIENT (disconnected)")
# Check for dead ReLUs
activations = model.layers[5].output
dead_neurons = tf.reduce_mean(tf.cast(activations <= 0, tf.float32))
```
**Solutions:**
```python
# For vanishing gradients
# Use He initialization for ReLU networks
initializer = tf.keras.initializers.HeNormal()
# Use LeakyReLU instead of ReLU
model.add(tf.keras.layers.LeakyReLU(alpha=0.1))
# Add residual connections (skip connections)
# For exploding gradients
# Apply gradient clipping
gradients, _ = tf.clip_by_global_norm(gradients, 5.0)
# Use proper weight initialization
initializer = tf.keras.initializers.GlorotUniform()
```
### 5. GPU Not Detected
**Symptoms:**
- `tf.config.list_physical_devices('GPU')` returns empty list
- Training runs on CPU (slow)
- CUDA errors on startup
**Diagnostic Steps:**
```python
# Check available devices
print("Physical devices:", tf.config.list_physical_devices())
print("GPU devices:", tf.config.list_physical_devices('GPU'))
print("Built with CUDA:", tf.test.is_built_with_cuda())
print("GPU available:", tf.test.is_gpu_available())
# Check CUDA/cuDNN versions
import subprocess
result = subprocess.run(['nvidia-smi'], capture_output=True, text=True)
print(result.stdout)
# Verify TensorFlow GPU package
import tensorflow as tf
print(tf.__version__)
print(tf.sysconfig.get_build_info())
```
**Common Causes:**
- Wrong TensorFlow package (CPU-only version)
- CUDA/cuDNN version mismatch
- NVIDIA driver issues
- GPU not visible to container (Docker)
**Solutions:**
```bash
# Install correct TensorFlow GPU package
pip install tensorflow[and-cuda] # TF 2.15+
# or
pip install tensorflow-gpu # Older versions
# Verify CUDA compatibility
# TF 2.15: CUDA 12.x, cuDNN 8.9
# TF 2.14: CUDA 11.8, cuDNN 8.7
# TF 2.13: CUDA 11.8, cuDNN 8.6
# For Docker, use nvidia-docker
docker run --gpus all -it tensorflow/tensorflow:latest-gpu
```
```python
# Force GPU visibility
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0' # Use first GPU
# Verify GPU is being used
with tf.device('/GPU:0'):
a = tf.constant([[1.0, 2.0], [3.0, 4.0]])
b = tf.constant([[1.0, 1.0], [0.0, 1.0]])
c = tf.matmul(a, b)
print(c.device) # Should show GPU
```
### 6. SavedModel Loading Errors
**Symptoms:**
- `OSError: SavedModel file does not exist`
- `ValueError: Unknown layer` when loading
- Version compatibility errors
**Diagnostic Steps:**
```python
# Check SavedModel structure
import os
for root, dirs, files in os.walk('saved_model_dir'):
for file in files:
print(os.path.join(root, file))
# Verify model signature
loaded = tf.saved_model.load('saved_model_dir')
print(list(loaded.signatures.keys()))
```
**Solutions:**
```python
# Save model correctly
model.save('my_model') # SavedModel format (recommended)
model.save('my_model.keras') # Keras format
# Load with custom objects
custom_objects = {
'CustomLayer': CustomLayer,
'custom_loss': custom_loss
}
model = tf.keras.models.load_model('my_model', custom_objects=custom_objects)
# For version mismatches, save weights only
model.save_weights('model_weights.weights.h5')
# Then rebuild model architecture and load weights
new_model.load_weights('model_weights.weights.h5')
```
### 7. Data Pipeline Issues
**Symptoms:**
- `InvalidArgumentError` during training
- Slow training (input bottleneck)
- Memory leaks during data loading
**Diagnostic Steps:**
```python
# Profile input pipeline
import tensorflow as tf
# Enable profiler
tf.profiler.experimental.start('/tmp/logdir')
# ... run training ...
tf.profiler.experimental.stop()
# Check dataset element spec
print(dataset.element_spec)
# Iterate and inspectRelated in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.