We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Add the example of super_resolution
Related to #2878 

Description: I have added the example for the super resolution in the `PyTorch/examples`

Check list:

- [x] New tests are added (if a new feature is added)
- [ ] New doc strings: description and/or example code are in RST format
- [ ] Documentation is updated (if required)


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `examples/super_resolution/main.py`
Content:
```
1 import argparse
2 
3 import torch
4 import torch.nn as nn
5 import torch.optim as optim
6 import torchvision
7 from model import Net
8 from torch.utils.data import DataLoader
9 from torchvision.transforms.functional import center_crop, resize, to_tensor
10 
11 from ignite.engine import Engine, Events
12 from ignite.metrics import PSNR
13 
14 # Training settings
15 parser = argparse.ArgumentParser(description="PyTorch Super Res Example")
16 parser.add_argument("--upscale_factor", type=int, required=True, help="super resolution upscale factor")
17 parser.add_argument("--batch_size", type=int, default=64, help="training batch size")
18 parser.add_argument("--test_batch_size", type=int, default=10, help="testing batch size")
19 parser.add_argument("--n_epochs", type=int, default=2, help="number of epochs to train for")
20 parser.add_argument("--lr", type=float, default=0.01, help="Learning Rate. Default=0.01")
21 parser.add_argument("--cuda", action="store_true", help="use cuda?")
22 parser.add_argument("--mps", action="store_true", default=False, help="enables macOS GPU training")
23 parser.add_argument("--threads", type=int, default=4, help="number of threads for data loader to use")
24 parser.add_argument("--seed", type=int, default=123, help="random seed to use. Default=123")
25 opt = parser.parse_args()
26 
27 print(opt)
28 
29 if opt.cuda and not torch.cuda.is_available():
30     raise Exception("No GPU found, please run without --cuda")
31 if not opt.mps and torch.backends.mps.is_available():
32     raise Exception("Found mps device, please run with --mps to enable macOS GPU")
33 
34 torch.manual_seed(opt.seed)
35 use_mps = opt.mps and torch.backends.mps.is_available()
36 
37 if opt.cuda:
38     device = torch.device("cuda")
39 elif use_mps:
40     device = torch.device("mps")
41 else:
42     device = torch.device("cpu")
43 
44 print("===> Loading datasets")
45 
46 
47 class SRDataset(torch.utils.data.Dataset):
48     def __init__(self, dataset, scale_factor, crop_size=256):
49         self.dataset = dataset
50         self.scale_factor = scale_factor
51         self.crop_size = crop_size
52 
53     def __getitem__(self, index):
54         image, _ = self.dataset[index]
55         img = image.convert("YCbCr")
56         hr_image, _, _ = img.split()
57         hr_image = center_crop(hr_image, self.crop_size)
58         lr_image = hr_image.copy()
59         if self.scale_factor != 1:
60             size = self.crop_size // self.scale_factor
61             lr_image = resize(lr_image, [size, size])
62         hr_image = to_tensor(hr_image)
63         lr_image = to_tensor(lr_image)
64         return lr_image, hr_image
65 
66     def __len__(self):
67         return len(self.dataset)
68 
69 
70 trainset = torchvision.datasets.Caltech101(root="./data", download=True)
71 testset = torchvision.datasets.Caltech101(root="./data", download=False)
72 
73 trainset_sr = SRDataset(trainset, scale_factor=opt.upscale_factor)
74 testset_sr = SRDataset(testset, scale_factor=opt.upscale_factor)
75 
76 training_data_loader = DataLoader(dataset=trainset_sr, num_workers=opt.threads, batch_size=opt.batch_size, shuffle=True)
77 testing_data_loader = DataLoader(dataset=testset_sr, num_workers=opt.threads, batch_size=opt.test_batch_size)
78 
79 print("===> Building model")
80 model = Net(upscale_factor=opt.upscale_factor).to(device)
81 criterion = nn.MSELoss()
82 
83 optimizer = optim.Adam(model.parameters(), lr=opt.lr)
84 
85 
86 def train_step(engine, batch):
87     model.train()
88     input, target = batch[0].to(device), batch[1].to(device)
89 
90     optimizer.zero_grad()
91     loss = criterion(model(input), target)
92     loss.backward()
93     optimizer.step()
94 
95     return loss.item()
96 
97 
98 def validation_step(engine, batch):
99     model.eval()
100     with torch.no_grad():
101         x, y = batch[0].to(device), batch[1].to(device)
102         y_pred = model(x)
103 
104     return y_pred, y
105 
106 
107 trainer = Engine(train_step)
108 evaluator = Engine(validation_step)
109 psnr = PSNR(data_range=1)
110 psnr.attach(evaluator, "psnr")
111 validate_every = 1
112 log_interval = 100
113 
114 
115 @trainer.on(Events.ITERATION_COMPLETED(every=log_interval))
116 def log_training_loss(engine):
117     print(
118         "===> Epoch[{}]({}/{}): Loss: {:.4f}".format(
119             engine.state.epoch, engine.state.iteration, len(training_data_loader), engine.state.output
120         )
121     )
122 
123 
124 @trainer.on(Events.EPOCH_COMPLETED(every=validate_every))
125 def log_validation():
126     evaluator.run(testing_data_loader)
127     metrics = evaluator.state.metrics
128     print(f"Epoch: {trainer.state.epoch}, Avg. PSNR: {metrics['psnr']} dB")
129 
130 
131 @trainer.on(Events.EPOCH_COMPLETED)
132 def log_epoch_time():
133     print(f"Epoch {trainer.state.epoch}, Time Taken : {trainer.state.times['EPOCH_COMPLETED']}")
134 
135 
136 @trainer.on(Events.COMPLETED)
137 def log_total_time():
138     print(f"Total Time: {trainer.state.times['COMPLETED']}")
139 
140 
141 @trainer.on(Events.EPOCH_COMPLETED)
142 def checkpoint():
143     model_out_path = "model_epoch_{}.pth".format(trainer.state.epoch)
144     torch.save(model, model_out_path)
145     print("Checkpoint saved to {}".format(model_out_path))
146 
147 
148 trainer.run(training_data_loader, opt.n_epochs)
149
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/examples/super_resolution/main.py b/examples/super_resolution/main.py
--- a/examples/super_resolution/main.py
+++ b/examples/super_resolution/main.py
@@ -8,11 +8,15 @@
 from torch.utils.data import DataLoader
 from torchvision.transforms.functional import center_crop, resize, to_tensor
 
+from ignite.contrib.handlers import ProgressBar
+
 from ignite.engine import Engine, Events
+from ignite.handlers import BasicTimeProfiler
 from ignite.metrics import PSNR
 
 # Training settings
 parser = argparse.ArgumentParser(description="PyTorch Super Res Example")
+parser.add_argument("--crop_size", type=int, default=256, help="cropped size of the images for training")
 parser.add_argument("--upscale_factor", type=int, required=True, help="super resolution upscale factor")
 parser.add_argument("--batch_size", type=int, default=64, help="training batch size")
 parser.add_argument("--test_batch_size", type=int, default=10, help="testing batch size")
@@ -22,6 +26,8 @@
 parser.add_argument("--mps", action="store_true", default=False, help="enables macOS GPU training")
 parser.add_argument("--threads", type=int, default=4, help="number of threads for data loader to use")
 parser.add_argument("--seed", type=int, default=123, help="random seed to use. Default=123")
+parser.add_argument("--debug", action="store_true", help="use debug")
+
 opt = parser.parse_args()
 
 print(opt)
@@ -70,8 +76,8 @@
 trainset = torchvision.datasets.Caltech101(root="./data", download=True)
 testset = torchvision.datasets.Caltech101(root="./data", download=False)
 
-trainset_sr = SRDataset(trainset, scale_factor=opt.upscale_factor)
-testset_sr = SRDataset(testset, scale_factor=opt.upscale_factor)
+trainset_sr = SRDataset(trainset, scale_factor=opt.upscale_factor, crop_size=opt.crop_size)
+testset_sr = SRDataset(testset, scale_factor=opt.upscale_factor, crop_size=opt.crop_size)
 
 training_data_loader = DataLoader(dataset=trainset_sr, num_workers=opt.threads, batch_size=opt.batch_size, shuffle=True)
 testing_data_loader = DataLoader(dataset=testset_sr, num_workers=opt.threads, batch_size=opt.test_batch_size)
@@ -109,35 +115,22 @@
 psnr = PSNR(data_range=1)
 psnr.attach(evaluator, "psnr")
 validate_every = 1
-log_interval = 100
-
 
-@trainer.on(Events.ITERATION_COMPLETED(every=log_interval))
-def log_training_loss(engine):
-    print(
-        "===> Epoch[{}]({}/{}): Loss: {:.4f}".format(
-            engine.state.epoch, engine.state.iteration, len(training_data_loader), engine.state.output
-        )
-    )
+if opt.debug:
+    epoch_length = 10
+    validate_epoch_length = 1
+else:
+    epoch_length = len(training_data_loader)
+    validate_epoch_length = len(testing_data_loader)
 
 
 @trainer.on(Events.EPOCH_COMPLETED(every=validate_every))
 def log_validation():
-    evaluator.run(testing_data_loader)
+    evaluator.run(testing_data_loader, epoch_length=validate_epoch_length)
     metrics = evaluator.state.metrics
     print(f"Epoch: {trainer.state.epoch}, Avg. PSNR: {metrics['psnr']} dB")
 
 
-@trainer.on(Events.EPOCH_COMPLETED)
-def log_epoch_time():
-    print(f"Epoch {trainer.state.epoch}, Time Taken : {trainer.state.times['EPOCH_COMPLETED']}")
-
-
-@trainer.on(Events.COMPLETED)
-def log_total_time():
-    print(f"Total Time: {trainer.state.times['COMPLETED']}")
-
-
 @trainer.on(Events.EPOCH_COMPLETED)
 def checkpoint():
     model_out_path = "model_epoch_{}.pth".format(trainer.state.epoch)
@@ -145,4 +138,13 @@
     print("Checkpoint saved to {}".format(model_out_path))
 
 
-trainer.run(training_data_loader, opt.n_epochs)
+# Attach basic profiler
+basic_profiler = BasicTimeProfiler()
+basic_profiler.attach(trainer)
+
+ProgressBar().attach(trainer, output_transform=lambda x: {"loss": x})
+
+trainer.run(training_data_loader, opt.n_epochs, epoch_length=epoch_length)
+
+results = basic_profiler.get_results()
+basic_profiler.print_results(results)

{"golden_diff": "diff --git a/examples/super_resolution/main.py b/examples/super_resolution/main.py\n--- a/examples/super_resolution/main.py\n+++ b/examples/super_resolution/main.py\n@@ -8,11 +8,15 @@\n from torch.utils.data import DataLoader\n from torchvision.transforms.functional import center_crop, resize, to_tensor\n \n+from ignite.contrib.handlers import ProgressBar\n+\n from ignite.engine import Engine, Events\n+from ignite.handlers import BasicTimeProfiler\n from ignite.metrics import PSNR\n \n # Training settings\n parser = argparse.ArgumentParser(description=\"PyTorch Super Res Example\")\n+parser.add_argument(\"--crop_size\", type=int, default=256, help=\"cropped size of the images for training\")\n parser.add_argument(\"--upscale_factor\", type=int, required=True, help=\"super resolution upscale factor\")\n parser.add_argument(\"--batch_size\", type=int, default=64, help=\"training batch size\")\n parser.add_argument(\"--test_batch_size\", type=int, default=10, help=\"testing batch size\")\n@@ -22,6 +26,8 @@\n parser.add_argument(\"--mps\", action=\"store_true\", default=False, help=\"enables macOS GPU training\")\n parser.add_argument(\"--threads\", type=int, default=4, help=\"number of threads for data loader to use\")\n parser.add_argument(\"--seed\", type=int, default=123, help=\"random seed to use. Default=123\")\n+parser.add_argument(\"--debug\", action=\"store_true\", help=\"use debug\")\n+\n opt = parser.parse_args()\n \n print(opt)\n@@ -70,8 +76,8 @@\n trainset = torchvision.datasets.Caltech101(root=\"./data\", download=True)\n testset = torchvision.datasets.Caltech101(root=\"./data\", download=False)\n \n-trainset_sr = SRDataset(trainset, scale_factor=opt.upscale_factor)\n-testset_sr = SRDataset(testset, scale_factor=opt.upscale_factor)\n+trainset_sr = SRDataset(trainset, scale_factor=opt.upscale_factor, crop_size=opt.crop_size)\n+testset_sr = SRDataset(testset, scale_factor=opt.upscale_factor, crop_size=opt.crop_size)\n \n training_data_loader = DataLoader(dataset=trainset_sr, num_workers=opt.threads, batch_size=opt.batch_size, shuffle=True)\n testing_data_loader = DataLoader(dataset=testset_sr, num_workers=opt.threads, batch_size=opt.test_batch_size)\n@@ -109,35 +115,22 @@\n psnr = PSNR(data_range=1)\n psnr.attach(evaluator, \"psnr\")\n validate_every = 1\n-log_interval = 100\n-\n \n-@trainer.on(Events.ITERATION_COMPLETED(every=log_interval))\n-def log_training_loss(engine):\n-    print(\n-        \"===> Epoch[{}]({}/{}): Loss: {:.4f}\".format(\n-            engine.state.epoch, engine.state.iteration, len(training_data_loader), engine.state.output\n-        )\n-    )\n+if opt.debug:\n+    epoch_length = 10\n+    validate_epoch_length = 1\n+else:\n+    epoch_length = len(training_data_loader)\n+    validate_epoch_length = len(testing_data_loader)\n \n \n @trainer.on(Events.EPOCH_COMPLETED(every=validate_every))\n def log_validation():\n-    evaluator.run(testing_data_loader)\n+    evaluator.run(testing_data_loader, epoch_length=validate_epoch_length)\n     metrics = evaluator.state.metrics\n     print(f\"Epoch: {trainer.state.epoch}, Avg. PSNR: {metrics['psnr']} dB\")\n \n \n-@trainer.on(Events.EPOCH_COMPLETED)\n-def log_epoch_time():\n-    print(f\"Epoch {trainer.state.epoch}, Time Taken : {trainer.state.times['EPOCH_COMPLETED']}\")\n-\n-\n-@trainer.on(Events.COMPLETED)\n-def log_total_time():\n-    print(f\"Total Time: {trainer.state.times['COMPLETED']}\")\n-\n-\n @trainer.on(Events.EPOCH_COMPLETED)\n def checkpoint():\n     model_out_path = \"model_epoch_{}.pth\".format(trainer.state.epoch)\n@@ -145,4 +138,13 @@\n     print(\"Checkpoint saved to {}\".format(model_out_path))\n \n \n-trainer.run(training_data_loader, opt.n_epochs)\n+# Attach basic profiler\n+basic_profiler = BasicTimeProfiler()\n+basic_profiler.attach(trainer)\n+\n+ProgressBar().attach(trainer, output_transform=lambda x: {\"loss\": x})\n+\n+trainer.run(training_data_loader, opt.n_epochs, epoch_length=epoch_length)\n+\n+results = basic_profiler.get_results()\n+basic_profiler.print_results(results)\n", "issue": "Add the example of super_resolution\nRelated to #2878 \r\n\r\nDescription: I have added the example for the super resolution in the `PyTorch/examples`\r\n\r\nCheck list:\r\n\r\n- [x] New tests are added (if a new feature is added)\r\n- [ ] New doc strings: description and/or example code are in RST format\r\n- [ ] Documentation is updated (if required)\r\n\n", "before_files": [{"content": "import argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nfrom model import Net\nfrom torch.utils.data import DataLoader\nfrom torchvision.transforms.functional import center_crop, resize, to_tensor\n\nfrom ignite.engine import Engine, Events\nfrom ignite.metrics import PSNR\n\n# Training settings\nparser = argparse.ArgumentParser(description=\"PyTorch Super Res Example\")\nparser.add_argument(\"--upscale_factor\", type=int, required=True, help=\"super resolution upscale factor\")\nparser.add_argument(\"--batch_size\", type=int, default=64, help=\"training batch size\")\nparser.add_argument(\"--test_batch_size\", type=int, default=10, help=\"testing batch size\")\nparser.add_argument(\"--n_epochs\", type=int, default=2, help=\"number of epochs to train for\")\nparser.add_argument(\"--lr\", type=float, default=0.01, help=\"Learning Rate. Default=0.01\")\nparser.add_argument(\"--cuda\", action=\"store_true\", help=\"use cuda?\")\nparser.add_argument(\"--mps\", action=\"store_true\", default=False, help=\"enables macOS GPU training\")\nparser.add_argument(\"--threads\", type=int, default=4, help=\"number of threads for data loader to use\")\nparser.add_argument(\"--seed\", type=int, default=123, help=\"random seed to use. Default=123\")\nopt = parser.parse_args()\n\nprint(opt)\n\nif opt.cuda and not torch.cuda.is_available():\n    raise Exception(\"No GPU found, please run without --cuda\")\nif not opt.mps and torch.backends.mps.is_available():\n    raise Exception(\"Found mps device, please run with --mps to enable macOS GPU\")\n\ntorch.manual_seed(opt.seed)\nuse_mps = opt.mps and torch.backends.mps.is_available()\n\nif opt.cuda:\n    device = torch.device(\"cuda\")\nelif use_mps:\n    device = torch.device(\"mps\")\nelse:\n    device = torch.device(\"cpu\")\n\nprint(\"===> Loading datasets\")\n\n\nclass SRDataset(torch.utils.data.Dataset):\n    def __init__(self, dataset, scale_factor, crop_size=256):\n        self.dataset = dataset\n        self.scale_factor = scale_factor\n        self.crop_size = crop_size\n\n    def __getitem__(self, index):\n        image, _ = self.dataset[index]\n        img = image.convert(\"YCbCr\")\n        hr_image, _, _ = img.split()\n        hr_image = center_crop(hr_image, self.crop_size)\n        lr_image = hr_image.copy()\n        if self.scale_factor != 1:\n            size = self.crop_size // self.scale_factor\n            lr_image = resize(lr_image, [size, size])\n        hr_image = to_tensor(hr_image)\n        lr_image = to_tensor(lr_image)\n        return lr_image, hr_image\n\n    def __len__(self):\n        return len(self.dataset)\n\n\ntrainset = torchvision.datasets.Caltech101(root=\"./data\", download=True)\ntestset = torchvision.datasets.Caltech101(root=\"./data\", download=False)\n\ntrainset_sr = SRDataset(trainset, scale_factor=opt.upscale_factor)\ntestset_sr = SRDataset(testset, scale_factor=opt.upscale_factor)\n\ntraining_data_loader = DataLoader(dataset=trainset_sr, num_workers=opt.threads, batch_size=opt.batch_size, shuffle=True)\ntesting_data_loader = DataLoader(dataset=testset_sr, num_workers=opt.threads, batch_size=opt.test_batch_size)\n\nprint(\"===> Building model\")\nmodel = Net(upscale_factor=opt.upscale_factor).to(device)\ncriterion = nn.MSELoss()\n\noptimizer = optim.Adam(model.parameters(), lr=opt.lr)\n\n\ndef train_step(engine, batch):\n    model.train()\n    input, target = batch[0].to(device), batch[1].to(device)\n\n    optimizer.zero_grad()\n    loss = criterion(model(input), target)\n    loss.backward()\n    optimizer.step()\n\n    return loss.item()\n\n\ndef validation_step(engine, batch):\n    model.eval()\n    with torch.no_grad():\n        x, y = batch[0].to(device), batch[1].to(device)\n        y_pred = model(x)\n\n    return y_pred, y\n\n\ntrainer = Engine(train_step)\nevaluator = Engine(validation_step)\npsnr = PSNR(data_range=1)\npsnr.attach(evaluator, \"psnr\")\nvalidate_every = 1\nlog_interval = 100\n\n\n@trainer.on(Events.ITERATION_COMPLETED(every=log_interval))\ndef log_training_loss(engine):\n    print(\n        \"===> Epoch[{}]({}/{}): Loss: {:.4f}\".format(\n            engine.state.epoch, engine.state.iteration, len(training_data_loader), engine.state.output\n        )\n    )\n\n\n@trainer.on(Events.EPOCH_COMPLETED(every=validate_every))\ndef log_validation():\n    evaluator.run(testing_data_loader)\n    metrics = evaluator.state.metrics\n    print(f\"Epoch: {trainer.state.epoch}, Avg. PSNR: {metrics['psnr']} dB\")\n\n\n@trainer.on(Events.EPOCH_COMPLETED)\ndef log_epoch_time():\n    print(f\"Epoch {trainer.state.epoch}, Time Taken : {trainer.state.times['EPOCH_COMPLETED']}\")\n\n\n@trainer.on(Events.COMPLETED)\ndef log_total_time():\n    print(f\"Total Time: {trainer.state.times['COMPLETED']}\")\n\n\n@trainer.on(Events.EPOCH_COMPLETED)\ndef checkpoint():\n    model_out_path = \"model_epoch_{}.pth\".format(trainer.state.epoch)\n    torch.save(model, model_out_path)\n    print(\"Checkpoint saved to {}\".format(model_out_path))\n\n\ntrainer.run(training_data_loader, opt.n_epochs)\n", "path": "examples/super_resolution/main.py"}], "after_files": [{"content": "import argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nfrom model import Net\nfrom torch.utils.data import DataLoader\nfrom torchvision.transforms.functional import center_crop, resize, to_tensor\n\nfrom ignite.contrib.handlers import ProgressBar\n\nfrom ignite.engine import Engine, Events\nfrom ignite.handlers import BasicTimeProfiler\nfrom ignite.metrics import PSNR\n\n# Training settings\nparser = argparse.ArgumentParser(description=\"PyTorch Super Res Example\")\nparser.add_argument(\"--crop_size\", type=int, default=256, help=\"cropped size of the images for training\")\nparser.add_argument(\"--upscale_factor\", type=int, required=True, help=\"super resolution upscale factor\")\nparser.add_argument(\"--batch_size\", type=int, default=64, help=\"training batch size\")\nparser.add_argument(\"--test_batch_size\", type=int, default=10, help=\"testing batch size\")\nparser.add_argument(\"--n_epochs\", type=int, default=2, help=\"number of epochs to train for\")\nparser.add_argument(\"--lr\", type=float, default=0.01, help=\"Learning Rate. Default=0.01\")\nparser.add_argument(\"--cuda\", action=\"store_true\", help=\"use cuda?\")\nparser.add_argument(\"--mps\", action=\"store_true\", default=False, help=\"enables macOS GPU training\")\nparser.add_argument(\"--threads\", type=int, default=4, help=\"number of threads for data loader to use\")\nparser.add_argument(\"--seed\", type=int, default=123, help=\"random seed to use. Default=123\")\nparser.add_argument(\"--debug\", action=\"store_true\", help=\"use debug\")\n\nopt = parser.parse_args()\n\nprint(opt)\n\nif opt.cuda and not torch.cuda.is_available():\n    raise Exception(\"No GPU found, please run without --cuda\")\nif not opt.mps and torch.backends.mps.is_available():\n    raise Exception(\"Found mps device, please run with --mps to enable macOS GPU\")\n\ntorch.manual_seed(opt.seed)\nuse_mps = opt.mps and torch.backends.mps.is_available()\n\nif opt.cuda:\n    device = torch.device(\"cuda\")\nelif use_mps:\n    device = torch.device(\"mps\")\nelse:\n    device = torch.device(\"cpu\")\n\nprint(\"===> Loading datasets\")\n\n\nclass SRDataset(torch.utils.data.Dataset):\n    def __init__(self, dataset, scale_factor, crop_size=256):\n        self.dataset = dataset\n        self.scale_factor = scale_factor\n        self.crop_size = crop_size\n\n    def __getitem__(self, index):\n        image, _ = self.dataset[index]\n        img = image.convert(\"YCbCr\")\n        hr_image, _, _ = img.split()\n        hr_image = center_crop(hr_image, self.crop_size)\n        lr_image = hr_image.copy()\n        if self.scale_factor != 1:\n            size = self.crop_size // self.scale_factor\n            lr_image = resize(lr_image, [size, size])\n        hr_image = to_tensor(hr_image)\n        lr_image = to_tensor(lr_image)\n        return lr_image, hr_image\n\n    def __len__(self):\n        return len(self.dataset)\n\n\ntrainset = torchvision.datasets.Caltech101(root=\"./data\", download=True)\ntestset = torchvision.datasets.Caltech101(root=\"./data\", download=False)\n\ntrainset_sr = SRDataset(trainset, scale_factor=opt.upscale_factor, crop_size=opt.crop_size)\ntestset_sr = SRDataset(testset, scale_factor=opt.upscale_factor, crop_size=opt.crop_size)\n\ntraining_data_loader = DataLoader(dataset=trainset_sr, num_workers=opt.threads, batch_size=opt.batch_size, shuffle=True)\ntesting_data_loader = DataLoader(dataset=testset_sr, num_workers=opt.threads, batch_size=opt.test_batch_size)\n\nprint(\"===> Building model\")\nmodel = Net(upscale_factor=opt.upscale_factor).to(device)\ncriterion = nn.MSELoss()\n\noptimizer = optim.Adam(model.parameters(), lr=opt.lr)\n\n\ndef train_step(engine, batch):\n    model.train()\n    input, target = batch[0].to(device), batch[1].to(device)\n\n    optimizer.zero_grad()\n    loss = criterion(model(input), target)\n    loss.backward()\n    optimizer.step()\n\n    return loss.item()\n\n\ndef validation_step(engine, batch):\n    model.eval()\n    with torch.no_grad():\n        x, y = batch[0].to(device), batch[1].to(device)\n        y_pred = model(x)\n\n    return y_pred, y\n\n\ntrainer = Engine(train_step)\nevaluator = Engine(validation_step)\npsnr = PSNR(data_range=1)\npsnr.attach(evaluator, \"psnr\")\nvalidate_every = 1\n\nif opt.debug:\n    epoch_length = 10\n    validate_epoch_length = 1\nelse:\n    epoch_length = len(training_data_loader)\n    validate_epoch_length = len(testing_data_loader)\n\n\n@trainer.on(Events.EPOCH_COMPLETED(every=validate_every))\ndef log_validation():\n    evaluator.run(testing_data_loader, epoch_length=validate_epoch_length)\n    metrics = evaluator.state.metrics\n    print(f\"Epoch: {trainer.state.epoch}, Avg. PSNR: {metrics['psnr']} dB\")\n\n\n@trainer.on(Events.EPOCH_COMPLETED)\ndef checkpoint():\n    model_out_path = \"model_epoch_{}.pth\".format(trainer.state.epoch)\n    torch.save(model, model_out_path)\n    print(\"Checkpoint saved to {}\".format(model_out_path))\n\n\n# Attach basic profiler\nbasic_profiler = BasicTimeProfiler()\nbasic_profiler.attach(trainer)\n\nProgressBar().attach(trainer, output_transform=lambda x: {\"loss\": x})\n\ntrainer.run(training_data_loader, opt.n_epochs, epoch_length=epoch_length)\n\nresults = basic_profiler.get_results()\nbasic_profiler.print_results(results)\n", "path": "examples/super_resolution/main.py"}]}