this is my code. there is an error about not being able to find a gpu. fix it: from IPython.display import clear_output
from pathlib import Path
from ray import tune, air
from ray.air import session, Checkpoint
from ray.tune.schedulers import PopulationBasedTraining
from torch.optim.lr_scheduler import StepLR
from torch.utils.data import Dataset, DataLoader
from torchvision.models import resnet50
from tqdm import tqdm
import cv2
import json
import math
import numpy as np
import optuna
import os
import random
import ray
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
Set Up
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
Set a random seed for torch
seed = 13
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # If using multiple GPUs
np.random.seed(seed)
random.seed(seed)
Additional configurations for deterministic behavior on CUDA devices
num_samples = 100 # None # Number of samples used for training. If None then all images
None # Number of samples used for validation. If None then all images
num_val_samples = 25
Tuple defining the input image shape (height, width)
input_shape = (224, 224)
num_classes = 4 # The possible rotation angles: 0, 90, 180, 270
Optuna Optimization Parameters
n_trials = 5 # Number of Optuna Trials
learning_rate_options = (1e-5, 1e-1) # Learning rate for the optimizer
batch_size_options = [8, 16] # Batch size for training
num_epochs_options = (5, 5) # Number of epochs to train the model for
weight_decay_options = (1e-6, 0.1)
dropout_rate_options = (0.001, 0.5)
def angle_difference(x, y):
"""
Calculate minimum difference between two angles.
"""
return 180 - abs(abs(x - y) - 180)
def angle_error(y_true, y_pred):
"""
Calculate the mean difference between the true angles
and the predicted angles.
"""
diff = angle_difference(y_true, y_pred)
return torch.mean(torch.abs(diff.float()))
Assistant
To fix the error about not being able to find a GPU, you can try the following steps:
Make sure that you have CUDA installed and configured properly on your system. You can check if CUDA is available by running torch.cuda.is_available().
If CUDA is available but you're still encountering the error, try updating your GPU drivers to the latest version.
If updating the drivers doesn't solve the issue, you can try setting the CUDA_VISIBLE_DEVICES environment variable to the index of your GPU. For example, if you have one GPU and it's indexed as 0, you can set os.environ["CUDA_VISIBLE_DEVICES"] = "0" before running the code.
If you're running the code in a Jupyter notebook, try restarting the kernel and running the code again.
If none of the above steps work, you can try running the code on CPU by changing device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') to device = torch.device('cpu').
Finally, if you're still unable to fix the issue, please provide more information about your system configuration and the exact error message that you're receiving.
User
how to fix: [2m[36m(train_model pid=114771)[0m ERROR: Unexpected bus error encountered in worker. This might be caused by insufficient shared memory (shm).
[2m[36m(train_model pid=114771)[0m
Assistant
To fix the "Unexpected bus error encountered in worker. This might be caused by insufficient shared memory (shm)" error, you can try the following steps:
Increase the shared memory size: The error message suggests that there might be insufficient shared memory (shm). You can try increasing the shared memory size by running the following command before running your code:
code
sudo sysctl -w kernel.shmmax=1000000000
This command increases the shared memory size to 1 GB. You can adjust the value as needed.
Check available shared memory: You can check the available shared memory on your system by running the following command:
code
df -h /dev/shm
Make sure that there is sufficient space available.
Rotation Related
def rotate(image, angle):
"""
Rotates an OpenCV 2 / NumPy image about its center by the given angle
(in degrees).
"""
center = (image.shape[1] / 2, image.shape[0] / 2)
rot_mat = cv2.getRotationMatrix2D(center, angle, 1.0)
return cv2.warpAffine(image, rot_mat, (image.shape[1], image.shape[0]), flags=cv2.INTER_LINEAR)
def largest_rotated_rect(w, h, angle):
"""
Given a rectangle of size wxh that has been rotated by 'angle' (in
radians), computes the width and height of the largest possible
axis-aligned rectangle within the rotated rectangle.
code
Original JS code by 'Andri' and Magnus Hoff from Stack Overflow
Converted to Python by Aaron Snoswell
Source: http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders
"""
quadrant = int(math.floor(angle / (math.pi / 2))) & 3
sign_alpha = angle if ((quadrant & 1) == 0) else math.pi - angle
alpha = (sign_alpha % math.pi + math.pi) % math.pi
bb_w = w * math.cos(alpha) + h * math.sin(alpha)
bb_h = w * math.sin(alpha) + h * math.cos(alpha)
gamma = math.atan2(bb_w, bb_w) if (w < h) else math.atan2(bb_w, bb_w)
delta = math.pi - alpha - gamma
length = h if (w < h) else w
d = length * math.cos(alpha)
a = d * math.sin(alpha) / math.sin(delta)
y = a * math.cos(gamma)
x = y * math.tan(gamma)
return (
bb_w - 2 * x,
bb_h - 2 * y
)
def crop_around_center(image, width, height):
"""
Given a NumPy / OpenCV 2 image, crops it to the given width and height,
around it's centre point
def crop_largest_rectangle(image, angle, height, width):
"""
Crop around the center the largest possible rectangle
found with largest_rotated_rect.
"""
return crop_around_center(
image,
*largest_rotated_rect(
width,
height,
math.radians(angle)
)
)
def generate_rotated_image(image, angle, size=None, crop_center=False,
crop_largest_rect=False):
"""
Generate a valid rotated image for the RotNetDataGenerator. If the
image is rectangular, the crop_center option should be used to make
it square. To crop out the black borders after rotation, use the
crop_largest_rect option. To resize the final image, use the size
option.
"""
height, width = image.shape[:2]
if crop_center:
if width < height:
height = width
else:
width = height
code
image = rotate(image, angle)
if crop_largest_rect:
image = crop_largest_rectangle(image, angle, height, width)
if size:
image = cv2.resize(image, size)
return image
# Recursively traverse the directory structure
for root, _, filenames in os.walk(path):
for filename in filenames:
image_paths.append(os.path.join(root, filename))
# Use all available images if num_samples is not provided
if num_samples is None:
train_filenames = image_paths
else:
# Randomly select num_samples images
train_filenames = random.sample(
image_paths, min(num_samples, len(image_paths)))
# Shuffle the train_filenames list
random.shuffle(train_filenames)
return train_filenames
if checkpoint_dir:
checkpoint_dict = session.get_checkpoint(checkpoint_dir)
if checkpoint_dict:
model.load_state_dict(checkpoint_dict["model_state_dict"])
optimizer.load_state_dict(checkpoint_dict["optimizer_state_dict"])
step = 1
while True:
model.train()
running_loss = 0.0
for i, data in enumerate(train_dataloader, 0):
inputs, labels = data['image'].to(device), data['angle'].to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
epoch_loss = running_loss / len(train_dataloader)
# Placeholder accuracy calculation
acc = 0.0
checkpoint = None
if step % config["checkpoint_interval"] == 0:
checkpoint = Checkpoint.from_dict({
"step": step,
"model_state_dict": model.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
})
session.report(
{"mean_accuracy": acc, "lr": config["lr"]},
checkpoint=checkpoint
)
step += 1
perturbation_interval = 5
scheduler = PopulationBasedTraining(
time_attr="training_iteration",
perturbation_interval=perturbation_interval,
metric="mean_accuracy",
mode="max",
hyperparam_mutations={
# distribution for resampling
"lr": tune.uniform(0.0001, 1),
# allow perturbations within this set of categorical values
"momentum": [0.8, 0.9, 0.99],
},
)
if ray.is_initialized():
ray.shutdown()
ray.init()
tuner = tune.Tuner(
train_model,
run_config=air.RunConfig(
name="pbt_test",
# Stop when we've reached a threshold accuracy, or a maximum
# training_iteration, whichever comes first
stop={"mean_accuracy": 0.96, "training_iteration": 50},
verbose=1,
checkpoint_config=air.CheckpointConfig(
checkpoint_score_attribute="mean_accuracy",
num_to_keep=4,
),
storage_path="/tmp/ray_results",
),
tune_config=tune.TuneConfig(
scheduler=scheduler,
num_samples=4,
),
param_space={
"lr": tune.uniform(0.001, 1),
"momentum": tune.uniform(0.001, 1),
"checkpoint_interval": perturbation_interval,
},
)
results_grid = tuner.fit()
Restart the Ray cluster: If you're running the code in a distributed Ray cluster, try restarting the cluster and running the code again. Sometimes the error can be caused by issues with the cluster setup.
Disable shared memory: If increasing the shared memory size doesn't resolve the issue, you can try disabling the use of shared memory by setting the RAY_USE_XRAY=1 environment variable before running your code. This will use a different mechanism for shared memory.
Provide more resources: If you're running the code on a cloud provider or a remote machine, make sure that you have allocated enough resources (e.g., CPU, memory) for your workload. Insufficient resources can sometimes cause bus errors.
If none of the above steps fix the issue, please provide more information about your system configuration and the exact error message that you're receiving.