You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
importosimportpytestimportrayimportray.trainastrainfromrayimporttune, cloudpicklefromray.tuneimportTuneErrorfromray.trainimportTrainerfromray.train.backendimportBackend, BackendConfigfromray.train.constantsimportTUNE_CHECKPOINT_FILE_NAMEfromray.train.worker_groupimportWorkerGroupimportargparsefromtypingimportDictimporttorchimportray.trainastrainfromray.train.trainerimportTrainerfromray.train.callbacksimportJsonLoggerCallbackfromtorchimportnnfromtorch.utils.dataimportDataLoaderfromtorchvisionimportdatasetsfromtorchvision.transformsimportToTensor# Download training data from open datasets.training_data=datasets.FashionMNIST(
root="~/data",
train=True,
download=True,
transform=ToTensor(),
)
# Download test data from open datasets.test_data=datasets.FashionMNIST(
root="~/data",
train=False,
download=True,
transform=ToTensor(),
)
# Define modelclassNeuralNetwork(nn.Module):
def__init__(self):
super(NeuralNetwork, self).__init__()
self.flatten=nn.Flatten()
self.linear_relu_stack=nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10),
nn.ReLU(),
)
defforward(self, x):
x=self.flatten(x)
logits=self.linear_relu_stack(x)
returnlogitsdeftrain_epoch(dataloader, model, loss_fn, optimizer):
size=len(dataloader.dataset) //train.world_size()
model.train()
forbatch, (X, y) inenumerate(dataloader):
# Compute prediction errorpred=model(X)
loss=loss_fn(pred, y)
# Backpropagationoptimizer.zero_grad()
loss.backward()
optimizer.step()
ifbatch%100==0:
loss, current=loss.item(), batch*len(X)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
defvalidate_epoch(dataloader, model, loss_fn):
size=len(dataloader.dataset) //train.world_size()
num_batches=len(dataloader)
model.eval()
test_loss, correct=0, 0withtorch.no_grad():
forX, yindataloader:
pred=model(X)
test_loss+=loss_fn(pred, y).item()
correct+= (pred.argmax(1) ==y).type(torch.float).sum().item()
test_loss/=num_batchescorrect/=sizeprint(
f"Test Error: \n "f"Accuracy: {(100*correct):>0.1f}%, "f"Avg loss: {test_loss:>8f}\n"
)
returntest_lossdeftrain_func(config: Dict):
batch_size=config["batch_size"]
lr=config["lr"]
epochs=config["epochs"]
worker_batch_size=batch_size//train.world_size()
# Create data loaders.train_dataloader=DataLoader(training_data, batch_size=worker_batch_size)
test_dataloader=DataLoader(test_data, batch_size=worker_batch_size)
train_dataloader=train.torch.prepare_data_loader(train_dataloader)
test_dataloader=train.torch.prepare_data_loader(test_dataloader)
# Create model.model=NeuralNetwork()
model=train.torch.prepare_model(model)
loss_fn=nn.CrossEntropyLoss()
optimizer=torch.optim.SGD(model.parameters(), lr=lr)
loss_results= []
for_inrange(epochs):
train_epoch(train_dataloader, model, loss_fn, optimizer)
loss=validate_epoch(test_dataloader, model, loss_fn)
train.report(loss=loss)
loss_results.append(loss)
returnloss_resultsdeftrain_fashion_mnist(num_workers=2, use_gpu=False):
trainer=Trainer(backend="torch", num_workers=num_workers, use_gpu=use_gpu)
trainer.start()
result=trainer.run(
train_func=train_func,
config={"lr": 1e-3, "batch_size": 64, "epochs": 4},
callbacks=[JsonLoggerCallback()],
)
trainer.shutdown()
print(f"Loss results: {result}")
@pytest.fixturedefray_start_2_cpus():
address_info=ray.init(num_cpus=2)
yieldaddress_info# The code after the yield will run as teardown code.ray.shutdown()
@pytest.fixturedefray_start_8_cpus():
address_info=ray.init(num_cpus=8)
yieldaddress_info# The code after the yield will run as teardown code.ray.shutdown()
classTestConfig(BackendConfig):
@propertydefbackend_cls(self):
returnTestBackendclassTestBackend(Backend):
defon_start(self, worker_group: WorkerGroup, backend_config: TestConfig):
passdefon_shutdown(self, worker_group: WorkerGroup, backend_config: TestConfig):
passdeftorch_fashion_mnist(num_workers, use_gpu, num_samples):
epochs=2trainer=Trainer("torch", num_workers=num_workers, use_gpu=use_gpu)
MnistTrainable=trainer.to_tune_trainable(train_func)
analysis=tune.run(
MnistTrainable,
num_samples=num_samples,
config={
"lr": tune.loguniform(1e-4, 1e-1),
"batch_size": tune.choice([32, 64, 128]),
"epochs": epochs,
},
)
# Check that loss decreases in each trial.forpath, dfinanalysis.trial_dataframes.items():
assertdf.loc[1, "loss"] <df.loc[0, "loss"]
deftest_tune_torch_fashion_mnist():
torch_fashion_mnist(num_workers=2, use_gpu=True, num_samples=2)
if__name__=='__main__':
ray.init()
test_tune_torch_fashion_mnist()
Issue Severity
High: It blocks me from completing my task.
The text was updated successfully, but these errors were encountered:
JiahaoYao
added
bug
Something that is supposed to be working; but isn't
triage
Needs triage (eg: priority, bug/not-bug, and owning component)
labels
Jul 13, 2022
What happened + What you expected to happen
This is the error message
Versions / Dependencies
ray 1.13
Reproduction script
Issue Severity
High: It blocks me from completing my task.
The text was updated successfully, but these errors were encountered: