prompt: You will be provided with a partial code base and an issue statement explaining a problem to resolve.
  <issue>
  Loftr does not work with some image size (not a memory issue)
  ### Describe the bug
  
  LoFTR incorrectly does something with positional embeddings
  ```
  RuntimeError                              Traceback (most recent call last)
  [<ipython-input-1-54d246337ab1>](https://9t3p2yszpxn-496ff2e9c6d22116-0-colab.googleusercontent.com/outputframe.html?vrz=colab-20220613-060046-RC00_454553376#) in <module>()
       10                 "image1": torch.rand(1,1, 1704, 2272).cuda()}
       11 with torch.no_grad():
  ---> 12     correspondences = matcher(input_dict)
  
  3 frames
  [/usr/local/lib/python3.7/dist-packages/kornia/feature/loftr/utils/position_encoding.py](https://9t3p2yszpxn-496ff2e9c6d22116-0-colab.googleusercontent.com/outputframe.html?vrz=colab-20220613-060046-RC00_454553376#) in forward(self, x)
       39             x: [N, C, H, W]
       40         """
  ---> 41         return x + self.pe[:, :, :x.size(2), :x.size(3)]
  
  RuntimeError: The size of tensor a (284) must match the size of tensor b (256) at non-singleton dimension 3
  ```
  
  ### Reproduction steps
  
  ```bash
  import kornia as K
  import kornia.feature as KF
  import numpy as np
  import torch
  
  matcher = KF.LoFTR(pretrained='outdoor').cuda()
  
  input_dict = {"image0": torch.rand(1,1, 1704, 2272),
                  "image1": torch.rand(1,1, 1704, 2272)}
  with torch.no_grad():
      correspondences = matcher(input_dict)
  ```
  
  
  ### Expected behavior
  
  Not an error 
  
  ### Environment
  
  ```shell
  not relevant
  ```
  
  
  ### Additional context
  
  _No response_
  
  </issue>
  <code>
  [start of kornia/feature/loftr/utils/position_encoding.py]
  1 import math
  2 
  3 import torch
  4 from torch import nn
  5 
  6 
  7 class PositionEncodingSine(nn.Module):
  8     """This is a sinusoidal position encoding that generalized to 2-dimensional images."""
  9 
  10     def __init__(self, d_model, max_shape=(256, 256), temp_bug_fix=True):
  11         """
  12         Args:
  13             max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels
  14             temp_bug_fix (bool): As noted in this [issue](https://github.com/zju3dv/LoFTR/issues/41),
  15                 the original implementation of LoFTR includes a bug in the pos-enc impl, which has little impact
  16                 on the final performance. For now, we keep both impls for backward compatibility.
  17                 We will remove the buggy impl after re-training all variants of our released models.
  18         """
  19         super().__init__()
  20 
  21         pe = torch.zeros((d_model, *max_shape))
  22         y_position = torch.ones(max_shape).cumsum(0).float().unsqueeze(0)
  23         x_position = torch.ones(max_shape).cumsum(1).float().unsqueeze(0)
  24         if temp_bug_fix:
  25             div_term = torch.exp(torch.arange(0, d_model // 2, 2).float() * (-math.log(10000.0) / (d_model // 2)))
  26         else:  # a buggy implementation (for backward compatibility only)
  27             div_term = torch.exp(torch.arange(0, d_model // 2, 2).float() * (-math.log(10000.0) / d_model // 2))
  28         div_term = div_term[:, None, None]  # [C//4, 1, 1]
  29         pe[0::4, :, :] = torch.sin(x_position * div_term)
  30         pe[1::4, :, :] = torch.cos(x_position * div_term)
  31         pe[2::4, :, :] = torch.sin(y_position * div_term)
  32         pe[3::4, :, :] = torch.cos(y_position * div_term)
  33 
  34         self.register_buffer('pe', pe.unsqueeze(0), persistent=False)  # [1, C, H, W]
  35 
  36     def forward(self, x):
  37         """
  38         Args:
  39             x: [N, C, H, W]
  40         """
  41         return x + self.pe[:, :, : x.size(2), : x.size(3)]
  42
  [end of kornia/feature/loftr/utils/position_encoding.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/kornia/feature/loftr/utils/position_encoding.py b/kornia/feature/loftr/utils/position_encoding.py
  --- a/kornia/feature/loftr/utils/position_encoding.py
  +++ b/kornia/feature/loftr/utils/position_encoding.py
  @@ -17,25 +17,51 @@
                   We will remove the buggy impl after re-training all variants of our released models.
           """
           super().__init__()
  +        self.d_model = d_model
  +        self.temp_bug_fix = temp_bug_fix
   
  -        pe = torch.zeros((d_model, *max_shape))
  +        pe = self._create_position_encoding(max_shape)
  +        self.register_buffer('pe', pe, persistent=False)  # [1, C, H, W]
  +
  +    def _create_position_encoding(self, max_shape):
  +        """Creates a position encoding from scratch.
  +
  +        For 1/8 feature map (which is standard): If the input image size is H, W (both divisible by 8), the max_shape
  +        should be (H//8, W//8).
  +        """
  +        pe = torch.zeros((self.d_model, *max_shape))
           y_position = torch.ones(max_shape).cumsum(0).float().unsqueeze(0)
           x_position = torch.ones(max_shape).cumsum(1).float().unsqueeze(0)
  -        if temp_bug_fix:
  -            div_term = torch.exp(torch.arange(0, d_model // 2, 2).float() * (-math.log(10000.0) / (d_model // 2)))
  +        if self.temp_bug_fix:
  +            div_term = torch.exp(
  +                torch.arange(0, self.d_model // 2, 2).float() * (-math.log(10000.0) / (self.d_model // 2))
  +            )
           else:  # a buggy implementation (for backward compatibility only)
  -            div_term = torch.exp(torch.arange(0, d_model // 2, 2).float() * (-math.log(10000.0) / d_model // 2))
  +            div_term = torch.exp(
  +                torch.arange(0, self.d_model // 2, 2).float() * (-math.log(10000.0) / self.d_model // 2)
  +            )
           div_term = div_term[:, None, None]  # [C//4, 1, 1]
           pe[0::4, :, :] = torch.sin(x_position * div_term)
           pe[1::4, :, :] = torch.cos(x_position * div_term)
           pe[2::4, :, :] = torch.sin(y_position * div_term)
           pe[3::4, :, :] = torch.cos(y_position * div_term)
  +        return pe.unsqueeze(0)
   
  -        self.register_buffer('pe', pe.unsqueeze(0), persistent=False)  # [1, C, H, W]
  +    def update_position_encoding_size(self, max_shape):
  +        """Updates position encoding to new max_shape.
  +
  +        For 1/8 feature map (which is standard): If the input image size is H, W (both divisible by 8), the max_shape
  +        should be (H//8, W//8).
  +        """
  +        self.pe = self._create_position_encoding(max_shape).to(self.pe.device)
   
       def forward(self, x):
           """
           Args:
               x: [N, C, H, W]
           """
  +        if x.size(2) > self.pe.size(2) or x.size(3) > self.pe.size(3):
  +            max_shape = (max(x.size(2), self.pe.size(2)), max(x.size(3), self.pe.size(3)))
  +            self.update_position_encoding_size(max_shape)
  +
           return x + self.pe[:, :, : x.size(2), : x.size(3)]
  
verification_info: {"golden_diff": "diff --git a/kornia/feature/loftr/utils/position_encoding.py b/kornia/feature/loftr/utils/position_encoding.py\n--- a/kornia/feature/loftr/utils/position_encoding.py\n+++ b/kornia/feature/loftr/utils/position_encoding.py\n@@ -17,25 +17,51 @@\n                 We will remove the buggy impl after re-training all variants of our released models.\n         \"\"\"\n         super().__init__()\n+        self.d_model = d_model\n+        self.temp_bug_fix = temp_bug_fix\n \n-        pe = torch.zeros((d_model, *max_shape))\n+        pe = self._create_position_encoding(max_shape)\n+        self.register_buffer('pe', pe, persistent=False)  # [1, C, H, W]\n+\n+    def _create_position_encoding(self, max_shape):\n+        \"\"\"Creates a position encoding from scratch.\n+\n+        For 1/8 feature map (which is standard): If the input image size is H, W (both divisible by 8), the max_shape\n+        should be (H//8, W//8).\n+        \"\"\"\n+        pe = torch.zeros((self.d_model, *max_shape))\n         y_position = torch.ones(max_shape).cumsum(0).float().unsqueeze(0)\n         x_position = torch.ones(max_shape).cumsum(1).float().unsqueeze(0)\n-        if temp_bug_fix:\n-            div_term = torch.exp(torch.arange(0, d_model // 2, 2).float() * (-math.log(10000.0) / (d_model // 2)))\n+        if self.temp_bug_fix:\n+            div_term = torch.exp(\n+                torch.arange(0, self.d_model // 2, 2).float() * (-math.log(10000.0) / (self.d_model // 2))\n+            )\n         else:  # a buggy implementation (for backward compatibility only)\n-            div_term = torch.exp(torch.arange(0, d_model // 2, 2).float() * (-math.log(10000.0) / d_model // 2))\n+            div_term = torch.exp(\n+                torch.arange(0, self.d_model // 2, 2).float() * (-math.log(10000.0) / self.d_model // 2)\n+            )\n         div_term = div_term[:, None, None]  # [C//4, 1, 1]\n         pe[0::4, :, :] = torch.sin(x_position * div_term)\n         pe[1::4, :, :] = torch.cos(x_position * div_term)\n         pe[2::4, :, :] = torch.sin(y_position * div_term)\n         pe[3::4, :, :] = torch.cos(y_position * div_term)\n+        return pe.unsqueeze(0)\n \n-        self.register_buffer('pe', pe.unsqueeze(0), persistent=False)  # [1, C, H, W]\n+    def update_position_encoding_size(self, max_shape):\n+        \"\"\"Updates position encoding to new max_shape.\n+\n+        For 1/8 feature map (which is standard): If the input image size is H, W (both divisible by 8), the max_shape\n+        should be (H//8, W//8).\n+        \"\"\"\n+        self.pe = self._create_position_encoding(max_shape).to(self.pe.device)\n \n     def forward(self, x):\n         \"\"\"\n         Args:\n             x: [N, C, H, W]\n         \"\"\"\n+        if x.size(2) > self.pe.size(2) or x.size(3) > self.pe.size(3):\n+            max_shape = (max(x.size(2), self.pe.size(2)), max(x.size(3), self.pe.size(3)))\n+            self.update_position_encoding_size(max_shape)\n+\n         return x + self.pe[:, :, : x.size(2), : x.size(3)]\n", "issue": "Loftr does not work with some image size (not a memory issue)\n### Describe the bug\n\nLoFTR incorrectly does something with positional embeddings\r\n```\r\nRuntimeError                              Traceback (most recent call last)\r\n[<ipython-input-1-54d246337ab1>](https://9t3p2yszpxn-496ff2e9c6d22116-0-colab.googleusercontent.com/outputframe.html?vrz=colab-20220613-060046-RC00_454553376#) in <module>()\r\n     10                 \"image1\": torch.rand(1,1, 1704, 2272).cuda()}\r\n     11 with torch.no_grad():\r\n---> 12     correspondences = matcher(input_dict)\r\n\r\n3 frames\r\n[/usr/local/lib/python3.7/dist-packages/kornia/feature/loftr/utils/position_encoding.py](https://9t3p2yszpxn-496ff2e9c6d22116-0-colab.googleusercontent.com/outputframe.html?vrz=colab-20220613-060046-RC00_454553376#) in forward(self, x)\r\n     39             x: [N, C, H, W]\r\n     40         \"\"\"\r\n---> 41         return x + self.pe[:, :, :x.size(2), :x.size(3)]\r\n\r\nRuntimeError: The size of tensor a (284) must match the size of tensor b (256) at non-singleton dimension 3\r\n```\n\n### Reproduction steps\n\n```bash\nimport kornia as K\r\nimport kornia.feature as KF\r\nimport numpy as np\r\nimport torch\r\n\r\nmatcher = KF.LoFTR(pretrained='outdoor').cuda()\r\n\r\ninput_dict = {\"image0\": torch.rand(1,1, 1704, 2272),\r\n                \"image1\": torch.rand(1,1, 1704, 2272)}\r\nwith torch.no_grad():\r\n    correspondences = matcher(input_dict)\n```\n\n\n### Expected behavior\n\nNot an error \n\n### Environment\n\n```shell\nnot relevant\n```\n\n\n### Additional context\n\n_No response_\n", "before_files": [{"content": "import math\n\nimport torch\nfrom torch import nn\n\n\nclass PositionEncodingSine(nn.Module):\n    \"\"\"This is a sinusoidal position encoding that generalized to 2-dimensional images.\"\"\"\n\n    def __init__(self, d_model, max_shape=(256, 256), temp_bug_fix=True):\n        \"\"\"\n        Args:\n            max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels\n            temp_bug_fix (bool): As noted in this [issue](https://github.com/zju3dv/LoFTR/issues/41),\n                the original implementation of LoFTR includes a bug in the pos-enc impl, which has little impact\n                on the final performance. For now, we keep both impls for backward compatibility.\n                We will remove the buggy impl after re-training all variants of our released models.\n        \"\"\"\n        super().__init__()\n\n        pe = torch.zeros((d_model, *max_shape))\n        y_position = torch.ones(max_shape).cumsum(0).float().unsqueeze(0)\n        x_position = torch.ones(max_shape).cumsum(1).float().unsqueeze(0)\n        if temp_bug_fix:\n            div_term = torch.exp(torch.arange(0, d_model // 2, 2).float() * (-math.log(10000.0) / (d_model // 2)))\n        else:  # a buggy implementation (for backward compatibility only)\n            div_term = torch.exp(torch.arange(0, d_model // 2, 2).float() * (-math.log(10000.0) / d_model // 2))\n        div_term = div_term[:, None, None]  # [C//4, 1, 1]\n        pe[0::4, :, :] = torch.sin(x_position * div_term)\n        pe[1::4, :, :] = torch.cos(x_position * div_term)\n        pe[2::4, :, :] = torch.sin(y_position * div_term)\n        pe[3::4, :, :] = torch.cos(y_position * div_term)\n\n        self.register_buffer('pe', pe.unsqueeze(0), persistent=False)  # [1, C, H, W]\n\n    def forward(self, x):\n        \"\"\"\n        Args:\n            x: [N, C, H, W]\n        \"\"\"\n        return x + self.pe[:, :, : x.size(2), : x.size(3)]\n", "path": "kornia/feature/loftr/utils/position_encoding.py"}]}