We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Error in transfer_batch_to_device when None type is in the batch
<!-- 
### Common bugs:
1. Tensorboard not showing in Jupyter-notebook see [issue 79](https://github.com/PyTorchLightning/pytorch-lightning/issues/79).    
2. PyTorch 1.1.0 vs 1.2.0 support [see FAQ](https://github.com/PyTorchLightning/pytorch-lightning#faq)    
-->

## 🐛 Bug

<!-- A clear and concise description of what the bug is. -->

### To Reproduce

Steps to reproduce the behavior:

1. There should be no `torchtext` pre-installed
2. Run the sample code

<!-- If you have a code sample, error messages, stack traces, please provide it here as well -->


#### Code sample
```import torch
from torch.utils.data import DataLoader
import pytorch_lightning as pl


def collate_fn(batch):
    return batch


class MyDataModule(pl.LightningDataModule):
    def __init__(self):
        super().__init__()

    def prepare_data(self):
        pass

    def setup(self, stage):
        self.train = [{"input": torch.randn(1,2), "output": None}]

    def train_dataloader(self):
        return DataLoader(self.train, batch_size=1, collate_fn=collate_fn)


class MyModel(pl.LightningModule):
    def __init__(self):
        super().__init__()
        self.linear = torch.nn.Linear(2, 1)

    def forward(self, x):
        return self.linear(x)

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters())

    def training_step(self, batch, batch_idx):
        x = batch[0]["input"]
        y = batch[0]["output"]
        loss = self(x)
        result = pl.TrainResult(loss)
        result.log('train_loss', loss, on_epoch=True)
        return result


def main():
    # Dataset
    data_module = MyDataModule()

    # Model
    model = MyModel()

    # Train
    trainer = pl.Trainer(max_steps=1)
    trainer.fit(model, datamodule=data_module)


if __name__ == "__main__":
    main()
```
<!-- Ideally attach a minimal code sample to reproduce the decried issue. 
Minimal means having the shortest code but still preserving the bug. -->

### Expected behavior
The above code runs fine if the package `torchtext` is installed. However, the code raises following error if `torchtext` is not available and I believe this inconsistency is a bug.

```
 File "python3.6/site-packages/pytorch_lightning/utilities/apply_func.py", line 122, in batch_to
    return data.to(device, **kwargs)
AttributeError: 'NoneType' object has no attribute 'to'
python-BaseException
```

I think this line of the [code](https://github.com/PyTorchLightning/pytorch-lightning/blob/f46318ebfeb785a659c49091a6871584ccde3ee1/pytorch_lightning/utilities/apply_func.py#L24) is the cause of the problem 

<!-- A clear and concise description of what you expected to happen. -->

### Environment
* CUDA:
	- GPU:
		- TITAN Xp
		- TITAN Xp
		- TITAN Xp
		- TITAN Xp
		- TITAN Xp
		- TITAN Xp
		- TITAN Xp
		- TITAN Xp
	- available:         True
	- version:           10.2
* Packages:
	- numpy:             1.18.4
	- pyTorch_debug:     False
	- pyTorch_version:   1.6.0
	- pytorch-lightning: 0.9.0
	- tensorboard:       2.2.1
	- tqdm:              4.46.0
* System:
	- OS:                Linux
	- architecture:
		- 64bit
		- ELF
	- processor:         x86_64
	- python:            3.6.8
	- version:           #81~16.04.1-Ubuntu SMP Tue Nov 26 16:34:21 UTC 2019


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pytorch_lightning/utilities/apply_func.py`
Content:
```
1 # Copyright The PyTorch Lightning team.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 import importlib
16 from abc import ABC
17 from collections.abc import Mapping, Sequence
18 from copy import copy
19 from typing import Any, Callable, Union
20 
21 import torch
22 
23 TORCHTEXT_AVAILABLE = importlib.util.find_spec("torchtext") is not None
24 if TORCHTEXT_AVAILABLE:
25     from torchtext.data import Batch
26 else:
27     Batch = type(None)
28 
29 
30 def apply_to_collection(data: Any, dtype: Union[type, tuple], function: Callable, *args, **kwargs) -> Any:
31     """
32     Recursively applies a function to all elements of a certain dtype.
33 
34     Args:
35         data: the collection to apply the function to
36         dtype: the given function will be applied to all elements of this dtype
37         function: the function to apply
38         *args: positional arguments (will be forwarded to calls of ``function``)
39         **kwargs: keyword arguments (will be forwarded to calls of ``function``)
40 
41     Returns:
42         the resulting collection
43 
44     """
45     elem_type = type(data)
46 
47     # Breaking condition
48     if isinstance(data, dtype):
49         return function(data, *args, **kwargs)
50 
51     # Recursively apply to collection items
52     elif isinstance(data, Mapping):
53         return elem_type({k: apply_to_collection(v, dtype, function, *args, **kwargs)
54                           for k, v in data.items()})
55     elif isinstance(data, tuple) and hasattr(data, '_fields'):  # named tuple
56         return elem_type(*(apply_to_collection(d, dtype, function, *args, **kwargs) for d in data))
57     elif isinstance(data, Sequence) and not isinstance(data, str):
58         return elem_type([apply_to_collection(d, dtype, function, *args, **kwargs) for d in data])
59 
60     # data is neither of dtype, nor a collection
61     return data
62 
63 
64 class TransferableDataType(ABC):
65     """
66     A custom type for data that can be moved to a torch device via `.to(...)`.
67 
68     Example:
69 
70         >>> isinstance(dict, TransferableDataType)
71         False
72         >>> isinstance(torch.rand(2, 3), TransferableDataType)
73         True
74         >>> class CustomObject:
75         ...     def __init__(self):
76         ...         self.x = torch.rand(2, 2)
77         ...     def to(self, device):
78         ...         self.x = self.x.to(device)
79         ...         return self
80         >>> isinstance(CustomObject(), TransferableDataType)
81         True
82     """
83 
84     @classmethod
85     def __subclasshook__(cls, subclass):
86         if cls is TransferableDataType:
87             to = getattr(subclass, "to", None)
88             return callable(to)
89         return NotImplemented
90 
91 
92 def move_data_to_device(batch: Any, device: torch.device):
93     """
94     Transfers a collection of data to the given device. Any object that defines a method
95     ``to(device)`` will be moved and all other objects in the collection will be left untouched.
96 
97     Args:
98         batch: A tensor or collection of tensors or anything that has a method `.to(...)`.
99             See :func:`apply_to_collection` for a list of supported collection types.
100         device: The device to which the data should be moved
101 
102     Return:
103         the same collection but with all contained tensors residing on the new device.
104 
105     See Also:
106         - :meth:`torch.Tensor.to`
107         - :class:`torch.device`
108     """
109 
110     def batch_to(data):
111         # try to move torchtext data first
112         if TORCHTEXT_AVAILABLE and isinstance(data, Batch):
113 
114             # Shallow copy because each Batch has a reference to Dataset which contains all examples
115             device_data = copy(data)
116             for field in data.fields:
117                 device_field = move_data_to_device(getattr(data, field), device)
118                 setattr(device_data, field, device_field)
119             return device_data
120 
121         kwargs = dict(non_blocking=True) if isinstance(data, torch.Tensor) else {}
122         return data.to(device, **kwargs)
123 
124     return apply_to_collection(batch, dtype=(TransferableDataType, Batch), function=batch_to)
125
```
--- 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/pytorch_lightning/utilities/apply_func.py b/pytorch_lightning/utilities/apply_func.py
--- a/pytorch_lightning/utilities/apply_func.py
+++ b/pytorch_lightning/utilities/apply_func.py
@@ -121,4 +121,5 @@
         kwargs = dict(non_blocking=True) if isinstance(data, torch.Tensor) else {}
         return data.to(device, **kwargs)
 
-    return apply_to_collection(batch, dtype=(TransferableDataType, Batch), function=batch_to)
+    dtype = (TransferableDataType, Batch) if TORCHTEXT_AVAILABLE else TransferableDataType
+    return apply_to_collection(batch, dtype=dtype, function=batch_to)

{"golden_diff": "diff --git a/pytorch_lightning/utilities/apply_func.py b/pytorch_lightning/utilities/apply_func.py\n--- a/pytorch_lightning/utilities/apply_func.py\n+++ b/pytorch_lightning/utilities/apply_func.py\n@@ -121,4 +121,5 @@\n         kwargs = dict(non_blocking=True) if isinstance(data, torch.Tensor) else {}\n         return data.to(device, **kwargs)\n \n-    return apply_to_collection(batch, dtype=(TransferableDataType, Batch), function=batch_to)\n+    dtype = (TransferableDataType, Batch) if TORCHTEXT_AVAILABLE else TransferableDataType\n+    return apply_to_collection(batch, dtype=dtype, function=batch_to)\n", "issue": "Error in transfer_batch_to_device when None type is in the batch\n<!-- \r\n### Common bugs:\r\n1. Tensorboard not showing in Jupyter-notebook see [issue 79](https://github.com/PyTorchLightning/pytorch-lightning/issues/79).    \r\n2. PyTorch 1.1.0 vs 1.2.0 support [see FAQ](https://github.com/PyTorchLightning/pytorch-lightning#faq)    \r\n-->\r\n\r\n## \ud83d\udc1b Bug\r\n\r\n<!-- A clear and concise description of what the bug is. -->\r\n\r\n### To Reproduce\r\n\r\nSteps to reproduce the behavior:\r\n\r\n1. There should be no `torchtext` pre-installed\r\n2. Run the sample code\r\n\r\n<!-- If you have a code sample, error messages, stack traces, please provide it here as well -->\r\n\r\n\r\n#### Code sample\r\n```import torch\r\nfrom torch.utils.data import DataLoader\r\nimport pytorch_lightning as pl\r\n\r\n\r\ndef collate_fn(batch):\r\n    return batch\r\n\r\n\r\nclass MyDataModule(pl.LightningDataModule):\r\n    def __init__(self):\r\n        super().__init__()\r\n\r\n    def prepare_data(self):\r\n        pass\r\n\r\n    def setup(self, stage):\r\n        self.train = [{\"input\": torch.randn(1,2), \"output\": None}]\r\n\r\n    def train_dataloader(self):\r\n        return DataLoader(self.train, batch_size=1, collate_fn=collate_fn)\r\n\r\n\r\nclass MyModel(pl.LightningModule):\r\n    def __init__(self):\r\n        super().__init__()\r\n        self.linear = torch.nn.Linear(2, 1)\r\n\r\n    def forward(self, x):\r\n        return self.linear(x)\r\n\r\n    def configure_optimizers(self):\r\n        return torch.optim.Adam(self.parameters())\r\n\r\n    def training_step(self, batch, batch_idx):\r\n        x = batch[0][\"input\"]\r\n        y = batch[0][\"output\"]\r\n        loss = self(x)\r\n        result = pl.TrainResult(loss)\r\n        result.log('train_loss', loss, on_epoch=True)\r\n        return result\r\n\r\n\r\ndef main():\r\n    # Dataset\r\n    data_module = MyDataModule()\r\n\r\n    # Model\r\n    model = MyModel()\r\n\r\n    # Train\r\n    trainer = pl.Trainer(max_steps=1)\r\n    trainer.fit(model, datamodule=data_module)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    main()\r\n```\r\n<!-- Ideally attach a minimal code sample to reproduce the decried issue. \r\nMinimal means having the shortest code but still preserving the bug. -->\r\n\r\n### Expected behavior\r\nThe above code runs fine if the package `torchtext` is installed. However, the code raises following error if `torchtext` is not available and I believe this inconsistency is a bug.\r\n\r\n```\r\n File \"python3.6/site-packages/pytorch_lightning/utilities/apply_func.py\", line 122, in batch_to\r\n    return data.to(device, **kwargs)\r\nAttributeError: 'NoneType' object has no attribute 'to'\r\npython-BaseException\r\n```\r\n\r\nI think this line of the [code](https://github.com/PyTorchLightning/pytorch-lightning/blob/f46318ebfeb785a659c49091a6871584ccde3ee1/pytorch_lightning/utilities/apply_func.py#L24) is the cause of the problem \r\n\r\n<!-- A clear and concise description of what you expected to happen. -->\r\n\r\n### Environment\r\n* CUDA:\r\n\t- GPU:\r\n\t\t- TITAN Xp\r\n\t\t- TITAN Xp\r\n\t\t- TITAN Xp\r\n\t\t- TITAN Xp\r\n\t\t- TITAN Xp\r\n\t\t- TITAN Xp\r\n\t\t- TITAN Xp\r\n\t\t- TITAN Xp\r\n\t- available:         True\r\n\t- version:           10.2\r\n* Packages:\r\n\t- numpy:             1.18.4\r\n\t- pyTorch_debug:     False\r\n\t- pyTorch_version:   1.6.0\r\n\t- pytorch-lightning: 0.9.0\r\n\t- tensorboard:       2.2.1\r\n\t- tqdm:              4.46.0\r\n* System:\r\n\t- OS:                Linux\r\n\t- architecture:\r\n\t\t- 64bit\r\n\t\t- ELF\r\n\t- processor:         x86_64\r\n\t- python:            3.6.8\r\n\t- version:           #81~16.04.1-Ubuntu SMP Tue Nov 26 16:34:21 UTC 2019\r\n\n", "before_files": [{"content": "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport importlib\nfrom abc import ABC\nfrom collections.abc import Mapping, Sequence\nfrom copy import copy\nfrom typing import Any, Callable, Union\n\nimport torch\n\nTORCHTEXT_AVAILABLE = importlib.util.find_spec(\"torchtext\") is not None\nif TORCHTEXT_AVAILABLE:\n    from torchtext.data import Batch\nelse:\n    Batch = type(None)\n\n\ndef apply_to_collection(data: Any, dtype: Union[type, tuple], function: Callable, *args, **kwargs) -> Any:\n    \"\"\"\n    Recursively applies a function to all elements of a certain dtype.\n\n    Args:\n        data: the collection to apply the function to\n        dtype: the given function will be applied to all elements of this dtype\n        function: the function to apply\n        *args: positional arguments (will be forwarded to calls of ``function``)\n        **kwargs: keyword arguments (will be forwarded to calls of ``function``)\n\n    Returns:\n        the resulting collection\n\n    \"\"\"\n    elem_type = type(data)\n\n    # Breaking condition\n    if isinstance(data, dtype):\n        return function(data, *args, **kwargs)\n\n    # Recursively apply to collection items\n    elif isinstance(data, Mapping):\n        return elem_type({k: apply_to_collection(v, dtype, function, *args, **kwargs)\n                          for k, v in data.items()})\n    elif isinstance(data, tuple) and hasattr(data, '_fields'):  # named tuple\n        return elem_type(*(apply_to_collection(d, dtype, function, *args, **kwargs) for d in data))\n    elif isinstance(data, Sequence) and not isinstance(data, str):\n        return elem_type([apply_to_collection(d, dtype, function, *args, **kwargs) for d in data])\n\n    # data is neither of dtype, nor a collection\n    return data\n\n\nclass TransferableDataType(ABC):\n    \"\"\"\n    A custom type for data that can be moved to a torch device via `.to(...)`.\n\n    Example:\n\n        >>> isinstance(dict, TransferableDataType)\n        False\n        >>> isinstance(torch.rand(2, 3), TransferableDataType)\n        True\n        >>> class CustomObject:\n        ...     def __init__(self):\n        ...         self.x = torch.rand(2, 2)\n        ...     def to(self, device):\n        ...         self.x = self.x.to(device)\n        ...         return self\n        >>> isinstance(CustomObject(), TransferableDataType)\n        True\n    \"\"\"\n\n    @classmethod\n    def __subclasshook__(cls, subclass):\n        if cls is TransferableDataType:\n            to = getattr(subclass, \"to\", None)\n            return callable(to)\n        return NotImplemented\n\n\ndef move_data_to_device(batch: Any, device: torch.device):\n    \"\"\"\n    Transfers a collection of data to the given device. Any object that defines a method\n    ``to(device)`` will be moved and all other objects in the collection will be left untouched.\n\n    Args:\n        batch: A tensor or collection of tensors or anything that has a method `.to(...)`.\n            See :func:`apply_to_collection` for a list of supported collection types.\n        device: The device to which the data should be moved\n\n    Return:\n        the same collection but with all contained tensors residing on the new device.\n\n    See Also:\n        - :meth:`torch.Tensor.to`\n        - :class:`torch.device`\n    \"\"\"\n\n    def batch_to(data):\n        # try to move torchtext data first\n        if TORCHTEXT_AVAILABLE and isinstance(data, Batch):\n\n            # Shallow copy because each Batch has a reference to Dataset which contains all examples\n            device_data = copy(data)\n            for field in data.fields:\n                device_field = move_data_to_device(getattr(data, field), device)\n                setattr(device_data, field, device_field)\n            return device_data\n\n        kwargs = dict(non_blocking=True) if isinstance(data, torch.Tensor) else {}\n        return data.to(device, **kwargs)\n\n    return apply_to_collection(batch, dtype=(TransferableDataType, Batch), function=batch_to)\n", "path": "pytorch_lightning/utilities/apply_func.py"}], "after_files": [{"content": "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport importlib\nfrom abc import ABC\nfrom collections.abc import Mapping, Sequence\nfrom copy import copy\nfrom typing import Any, Callable, Union\n\nimport torch\n\nTORCHTEXT_AVAILABLE = importlib.util.find_spec(\"torchtext\") is not None\nif TORCHTEXT_AVAILABLE:\n    from torchtext.data import Batch\nelse:\n    Batch = type(None)\n\n\ndef apply_to_collection(data: Any, dtype: Union[type, tuple], function: Callable, *args, **kwargs) -> Any:\n    \"\"\"\n    Recursively applies a function to all elements of a certain dtype.\n\n    Args:\n        data: the collection to apply the function to\n        dtype: the given function will be applied to all elements of this dtype\n        function: the function to apply\n        *args: positional arguments (will be forwarded to calls of ``function``)\n        **kwargs: keyword arguments (will be forwarded to calls of ``function``)\n\n    Returns:\n        the resulting collection\n\n    \"\"\"\n    elem_type = type(data)\n\n    # Breaking condition\n    if isinstance(data, dtype):\n        return function(data, *args, **kwargs)\n\n    # Recursively apply to collection items\n    elif isinstance(data, Mapping):\n        return elem_type({k: apply_to_collection(v, dtype, function, *args, **kwargs)\n                          for k, v in data.items()})\n    elif isinstance(data, tuple) and hasattr(data, '_fields'):  # named tuple\n        return elem_type(*(apply_to_collection(d, dtype, function, *args, **kwargs) for d in data))\n    elif isinstance(data, Sequence) and not isinstance(data, str):\n        return elem_type([apply_to_collection(d, dtype, function, *args, **kwargs) for d in data])\n\n    # data is neither of dtype, nor a collection\n    return data\n\n\nclass TransferableDataType(ABC):\n    \"\"\"\n    A custom type for data that can be moved to a torch device via `.to(...)`.\n\n    Example:\n\n        >>> isinstance(dict, TransferableDataType)\n        False\n        >>> isinstance(torch.rand(2, 3), TransferableDataType)\n        True\n        >>> class CustomObject:\n        ...     def __init__(self):\n        ...         self.x = torch.rand(2, 2)\n        ...     def to(self, device):\n        ...         self.x = self.x.to(device)\n        ...         return self\n        >>> isinstance(CustomObject(), TransferableDataType)\n        True\n    \"\"\"\n\n    @classmethod\n    def __subclasshook__(cls, subclass):\n        if cls is TransferableDataType:\n            to = getattr(subclass, \"to\", None)\n            return callable(to)\n        return NotImplemented\n\n\ndef move_data_to_device(batch: Any, device: torch.device):\n    \"\"\"\n    Transfers a collection of data to the given device. Any object that defines a method\n    ``to(device)`` will be moved and all other objects in the collection will be left untouched.\n\n    Args:\n        batch: A tensor or collection of tensors or anything that has a method `.to(...)`.\n            See :func:`apply_to_collection` for a list of supported collection types.\n        device: The device to which the data should be moved\n\n    Return:\n        the same collection but with all contained tensors residing on the new device.\n\n    See Also:\n        - :meth:`torch.Tensor.to`\n        - :class:`torch.device`\n    \"\"\"\n\n    def batch_to(data):\n        # try to move torchtext data first\n        if TORCHTEXT_AVAILABLE and isinstance(data, Batch):\n\n            # Shallow copy because each Batch has a reference to Dataset which contains all examples\n            device_data = copy(data)\n            for field in data.fields:\n                device_field = move_data_to_device(getattr(data, field), device)\n                setattr(device_data, field, device_field)\n            return device_data\n\n        kwargs = dict(non_blocking=True) if isinstance(data, torch.Tensor) else {}\n        return data.to(device, **kwargs)\n\n    dtype = (TransferableDataType, Batch) if TORCHTEXT_AVAILABLE else TransferableDataType\n    return apply_to_collection(batch, dtype=dtype, function=batch_to)\n", "path": "pytorch_lightning/utilities/apply_func.py"}]}