prompt: You will be provided with a partial code base and an issue statement explaining a problem to resolve.
  <issue>
  Bug in `CVAE` example
  There is a bug in `CVAE` example. The `target` input to the `MaskedBCELoss` is not binary (it has values of -1, 0, 1). This was discovered by the PyTorch 2.1 update which started to validate the inputs of `F.binary_cross_entropy_loss`.
  
  > FAILED tests/test_examples.py::test_cpu[cvae/main.py --num-quadrant-inputs=1 --num-epochs=1] - subprocess.CalledProcessError: Command '['/opt/hostedtoolcache/Python/3.8.18/x64/bin/python', '/home/runner/work/pyro/pyro/examples/cvae/main.py', '--num-quadrant-inputs=1', '--num-epochs=1']' returned non-zero exit status 1.
  = 1 failed, 148 passed, 97 skipped, 26558 deselected, 2 warnings in 1948.89s (0:32:28) =
  
  </issue>
  <code>
  [start of examples/cvae/baseline.py]
  1 # Copyright Contributors to the Pyro project.
  2 # SPDX-License-Identifier: Apache-2.0
  3 
  4 import copy
  5 from pathlib import Path
  6 
  7 import numpy as np
  8 import torch
  9 import torch.nn as nn
  10 import torch.nn.functional as F
  11 from tqdm import tqdm
  12 
  13 
  14 class BaselineNet(nn.Module):
  15     def __init__(self, hidden_1, hidden_2):
  16         super().__init__()
  17         self.fc1 = nn.Linear(784, hidden_1)
  18         self.fc2 = nn.Linear(hidden_1, hidden_2)
  19         self.fc3 = nn.Linear(hidden_2, 784)
  20         self.relu = nn.ReLU()
  21 
  22     def forward(self, x):
  23         x = x.view(-1, 784)
  24         hidden = self.relu(self.fc1(x))
  25         hidden = self.relu(self.fc2(hidden))
  26         y = torch.sigmoid(self.fc3(hidden))
  27         return y
  28 
  29 
  30 class MaskedBCELoss(nn.Module):
  31     def __init__(self, masked_with=-1):
  32         super().__init__()
  33         self.masked_with = masked_with
  34 
  35     def forward(self, input, target):
  36         target = target.view(input.shape)
  37         loss = F.binary_cross_entropy(input, target, reduction="none")
  38         loss[target == self.masked_with] = 0
  39         return loss.sum()
  40 
  41 
  42 def train(
  43     device,
  44     dataloaders,
  45     dataset_sizes,
  46     learning_rate,
  47     num_epochs,
  48     early_stop_patience,
  49     model_path,
  50 ):
  51     # Train baseline
  52     baseline_net = BaselineNet(500, 500)
  53     baseline_net.to(device)
  54     optimizer = torch.optim.Adam(baseline_net.parameters(), lr=learning_rate)
  55     criterion = MaskedBCELoss()
  56     best_loss = np.inf
  57     early_stop_count = 0
  58 
  59     for epoch in range(num_epochs):
  60         for phase in ["train", "val"]:
  61             if phase == "train":
  62                 baseline_net.train()
  63             else:
  64                 baseline_net.eval()
  65 
  66             running_loss = 0.0
  67             num_preds = 0
  68 
  69             bar = tqdm(
  70                 dataloaders[phase], desc="NN Epoch {} {}".format(epoch, phase).ljust(20)
  71             )
  72             for i, batch in enumerate(bar):
  73                 inputs = batch["input"].to(device)
  74                 outputs = batch["output"].to(device)
  75 
  76                 optimizer.zero_grad()
  77 
  78                 with torch.set_grad_enabled(phase == "train"):
  79                     preds = baseline_net(inputs)
  80                     loss = criterion(preds, outputs) / inputs.size(0)
  81                     if phase == "train":
  82                         loss.backward()
  83                         optimizer.step()
  84 
  85                 running_loss += loss.item()
  86                 num_preds += 1
  87                 if i % 10 == 0:
  88                     bar.set_postfix(
  89                         loss="{:.2f}".format(running_loss / num_preds),
  90                         early_stop_count=early_stop_count,
  91                     )
  92 
  93             epoch_loss = running_loss / dataset_sizes[phase]
  94             # deep copy the model
  95             if phase == "val":
  96                 if epoch_loss < best_loss:
  97                     best_loss = epoch_loss
  98                     best_model_wts = copy.deepcopy(baseline_net.state_dict())
  99                     early_stop_count = 0
  100                 else:
  101                     early_stop_count += 1
  102 
  103         if early_stop_count >= early_stop_patience:
  104             break
  105 
  106     baseline_net.load_state_dict(best_model_wts)
  107     baseline_net.eval()
  108 
  109     # Save model weights
  110     Path(model_path).parent.mkdir(parents=True, exist_ok=True)
  111     torch.save(baseline_net.state_dict(), model_path)
  112 
  113     return baseline_net
  114
  [end of examples/cvae/baseline.py]
  </code>
  
  I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format.
  <patch>
  diff --git a/file.py b/file.py
  --- a/file.py
  +++ b/file.py
  @@ -1,27 +1,35 @@
   def euclidean(a, b):
  -    while b:
  -        a, b = b, a % b
  -    return a
  +    if b == 0:
  +        return a
  +    return euclidean(b, a % b)
   
   
   def bresenham(x0, y0, x1, y1):
       points = []
       dx = abs(x1 - x0)
       dy = abs(y1 - y0)
  -    sx = 1 if x0 < x1 else -1
  -    sy = 1 if y0 < y1 else -1
  -    err = dx - dy
  +    x, y = x0, y0
  +    sx = -1 if x0 > x1 else 1
  +    sy = -1 if y0 > y1 else 1
   
  -    while True:
  -        points.append((x0, y0))
  -        if x0 == x1 and y0 == y1:
  -            break
  -        e2 = 2 * err
  -        if e2 > -dy:
  -            err -= dy
  -            x0 += sx
  -        if e2 < dx:
  -            err += dx
  -            y0 += sy
  +    if dx > dy:
  +        err = dx / 2.0
  +        while x != x1:
  +            points.append((x, y))
  +            err -= dy
  +            if err < 0:
  +                y += sy
  +                err += dx
  +            x += sx
  +    else:
  +        err = dy / 2.0
  +        while y != y1:
  +            points.append((x, y))
  +            err -= dx
  +            if err < 0:
  +                x += sx
  +                err += dy
  +            y += sy
  +
  +    points.append((x, y))
       return points
  
  </patch>
golden_diff: diff --git a/examples/cvae/baseline.py b/examples/cvae/baseline.py
  --- a/examples/cvae/baseline.py
  +++ b/examples/cvae/baseline.py
  @@ -34,8 +34,12 @@
   
       def forward(self, input, target):
           target = target.view(input.shape)
  -        loss = F.binary_cross_entropy(input, target, reduction="none")
  -        loss[target == self.masked_with] = 0
  +        # only calculate loss on target pixels (value = -1)
  +        loss = F.binary_cross_entropy(
  +            input[target != self.masked_with],
  +            target[target != self.masked_with],
  +            reduction="none",
  +        )
           return loss.sum()
  
verification_info: {"golden_diff": "diff --git a/examples/cvae/baseline.py b/examples/cvae/baseline.py\n--- a/examples/cvae/baseline.py\n+++ b/examples/cvae/baseline.py\n@@ -34,8 +34,12 @@\n \n     def forward(self, input, target):\n         target = target.view(input.shape)\n-        loss = F.binary_cross_entropy(input, target, reduction=\"none\")\n-        loss[target == self.masked_with] = 0\n+        # only calculate loss on target pixels (value = -1)\n+        loss = F.binary_cross_entropy(\n+            input[target != self.masked_with],\n+            target[target != self.masked_with],\n+            reduction=\"none\",\n+        )\n         return loss.sum()\n", "issue": "Bug in `CVAE` example\nThere is a bug in `CVAE` example. The `target` input to the `MaskedBCELoss` is not binary (it has values of -1, 0, 1). This was discovered by the PyTorch 2.1 update which started to validate the inputs of `F.binary_cross_entropy_loss`.\r\n\r\n> FAILED tests/test_examples.py::test_cpu[cvae/main.py --num-quadrant-inputs=1 --num-epochs=1] - subprocess.CalledProcessError: Command '['/opt/hostedtoolcache/Python/3.8.18/x64/bin/python', '/home/runner/work/pyro/pyro/examples/cvae/main.py', '--num-quadrant-inputs=1', '--num-epochs=1']' returned non-zero exit status 1.\r\n= 1 failed, 148 passed, 97 skipped, 26558 deselected, 2 warnings in 1948.89s (0:32:28) =\n", "before_files": [{"content": "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nimport copy\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom tqdm import tqdm\n\n\nclass BaselineNet(nn.Module):\n    def __init__(self, hidden_1, hidden_2):\n        super().__init__()\n        self.fc1 = nn.Linear(784, hidden_1)\n        self.fc2 = nn.Linear(hidden_1, hidden_2)\n        self.fc3 = nn.Linear(hidden_2, 784)\n        self.relu = nn.ReLU()\n\n    def forward(self, x):\n        x = x.view(-1, 784)\n        hidden = self.relu(self.fc1(x))\n        hidden = self.relu(self.fc2(hidden))\n        y = torch.sigmoid(self.fc3(hidden))\n        return y\n\n\nclass MaskedBCELoss(nn.Module):\n    def __init__(self, masked_with=-1):\n        super().__init__()\n        self.masked_with = masked_with\n\n    def forward(self, input, target):\n        target = target.view(input.shape)\n        loss = F.binary_cross_entropy(input, target, reduction=\"none\")\n        loss[target == self.masked_with] = 0\n        return loss.sum()\n\n\ndef train(\n    device,\n    dataloaders,\n    dataset_sizes,\n    learning_rate,\n    num_epochs,\n    early_stop_patience,\n    model_path,\n):\n    # Train baseline\n    baseline_net = BaselineNet(500, 500)\n    baseline_net.to(device)\n    optimizer = torch.optim.Adam(baseline_net.parameters(), lr=learning_rate)\n    criterion = MaskedBCELoss()\n    best_loss = np.inf\n    early_stop_count = 0\n\n    for epoch in range(num_epochs):\n        for phase in [\"train\", \"val\"]:\n            if phase == \"train\":\n                baseline_net.train()\n            else:\n                baseline_net.eval()\n\n            running_loss = 0.0\n            num_preds = 0\n\n            bar = tqdm(\n                dataloaders[phase], desc=\"NN Epoch {} {}\".format(epoch, phase).ljust(20)\n            )\n            for i, batch in enumerate(bar):\n                inputs = batch[\"input\"].to(device)\n                outputs = batch[\"output\"].to(device)\n\n                optimizer.zero_grad()\n\n                with torch.set_grad_enabled(phase == \"train\"):\n                    preds = baseline_net(inputs)\n                    loss = criterion(preds, outputs) / inputs.size(0)\n                    if phase == \"train\":\n                        loss.backward()\n                        optimizer.step()\n\n                running_loss += loss.item()\n                num_preds += 1\n                if i % 10 == 0:\n                    bar.set_postfix(\n                        loss=\"{:.2f}\".format(running_loss / num_preds),\n                        early_stop_count=early_stop_count,\n                    )\n\n            epoch_loss = running_loss / dataset_sizes[phase]\n            # deep copy the model\n            if phase == \"val\":\n                if epoch_loss < best_loss:\n                    best_loss = epoch_loss\n                    best_model_wts = copy.deepcopy(baseline_net.state_dict())\n                    early_stop_count = 0\n                else:\n                    early_stop_count += 1\n\n        if early_stop_count >= early_stop_patience:\n            break\n\n    baseline_net.load_state_dict(best_model_wts)\n    baseline_net.eval()\n\n    # Save model weights\n    Path(model_path).parent.mkdir(parents=True, exist_ok=True)\n    torch.save(baseline_net.state_dict(), model_path)\n\n    return baseline_net\n", "path": "examples/cvae/baseline.py"}]}