{"id":47567,"date":"2026-11-23T22:06:06","date_gmt":"2026-11-23T22:06:06","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=47567"},"modified":"2026-11-23T22:06:06","modified_gmt":"2026-11-23T22:06:06","slug":"pytorch-lab-4-pytorch-cuda-semantics","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/pytorch-lab-4-pytorch-cuda-semantics\/","title":{"rendered":"PyTorch Lab -4 &#8211; Pytorch CUDA Semantics"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This lab covers how PyTorch places tensors on GPUs: device objects, the current device, moving tensors between the CPU and GPUs, and how the CUDA caching allocator reports memory. The notebook above runs these APIs on a two-GPU machine. The sections below explain what each cell shows, update the deprecated calls, and list the errors you are most likely to hit when working with more than one device.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/148566466469e2a1c77f1e1d26e20743.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What CUDA semantics means in PyTorch<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Every PyTorch tensor belongs to one device, such as <code>cpu<\/code>, <code>cuda:0<\/code> or <code>cuda:1<\/code>. PyTorch never moves data between devices without being told to. An operation needs all of its tensor inputs on the same device, and the result is created on that device. Data only moves when you call <code>.to()<\/code>, <code>.cuda()<\/code> or <code>.cpu()<\/code>, or when you pass a <code>device=<\/code> argument when creating a tensor.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">PyTorch also keeps track of a <strong>current device<\/strong> for each process, which starts as <code>cuda:0<\/code>. A bare <code>torch.device(&#039;cuda&#039;)<\/code> or a call to <code>.cuda()<\/code> with no index points to the current device. <code>with torch.cuda.device(n):<\/code> changes the current device only inside that block. That is why <code>a1<\/code> in the example above ended up on <code>cuda:1<\/code> while <code>a0<\/code>, which named <code>cuda0<\/code> explicitly, stayed on <code>cuda:0<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">GPU work is also <strong>asynchronous<\/strong>. A CUDA operation is queued on a stream and control returns to Python before the GPU finishes. Copies between devices and calls like <code>.item()<\/code> or <code>print(tensor)<\/code> wait for the GPU automatically. Timing code and error reporting have to account for this, as later sections explain.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites and environment check<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>An NVIDIA GPU with a working driver. <code>nvidia-smi<\/code> should list every GPU you expect.<\/li>\n\n\n<li>A PyTorch build with CUDA support. The default CPU-only wheels always return <code>False<\/code> from <code>torch.cuda.is_available()<\/code>.<\/li>\n\n\n<li>Two or more GPUs for the cross-device cells. On a single GPU, every <code>cuda:1<\/code> cell fails with <code>invalid device ordinal<\/code>, the same way the <code>cuda:2<\/code> cell does above.<\/li>\n<\/ul>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">nvidia-smi --query-gpu=index,name,memory.total --format=csv\npython -c <span class=\"hljs-string\">\"import torch; print(torch.__version__, torch.version.cuda, torch.cuda.is_available(), torch.cuda.device_count())\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">When <code>torch.version.cuda<\/code> prints <code>None<\/code>, the installed PyTorch was built without CUDA. Reinstall it using the CUDA-enabled command from the PyTorch install selector for your platform.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The APIs used in the notebook<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Call<\/th><th>What it does<\/th><th>Notes<\/th><\/tr><\/thead><tbody><tr><td><code>torch.cuda.is_available()<\/code><\/td><td>Returns True if PyTorch can see at least one usable GPU<\/td><td>Check this before any CUDA call<\/td><\/tr><tr><td><code>torch.cuda.init()<\/code><\/td><td>Forces CUDA initialisation<\/td><td>Rarely needed. PyTorch initialises CUDA lazily on first use<\/td><\/tr><tr><td><code>torch.cuda.current_device()<\/code><\/td><td>Index of the current device<\/td><td>Starts at 0. Changed by <code>torch.cuda.device<\/code> or <code>torch.cuda.set_device<\/code><\/td><\/tr><tr><td><code>torch.cuda.device_count()<\/code><\/td><td>Number of visible GPUs<\/td><td>Respects <code>CUDA_VISIBLE_DEVICES<\/code><\/td><\/tr><tr><td><code>torch.device(&#039;cuda:2&#039;)<\/code><\/td><td>Creates a device descriptor<\/td><td>Does not check that the GPU exists. The error appears when you allocate on it<\/td><\/tr><tr><td><code>x.cuda()<\/code> \/ <code>x.to(device)<\/code><\/td><td>Copies to a GPU<\/td><td>Returns the same tensor, without copying, if it is already on the target device<\/td><\/tr><tr><td><code>with torch.cuda.device(1):<\/code><\/td><td>Temporarily changes the current device<\/td><td>Affects only calls that do not name a device index<\/td><\/tr><tr><td><code>torch.cuda.memory_allocated()<\/code><\/td><td>Bytes held by live tensors on the current device<\/td><td>Pass a device to query another GPU<\/td><\/tr><tr><td><code>torch.cuda.memory_reserved()<\/code><\/td><td>Bytes held by the caching allocator<\/td><td>Replaces the deprecated <code>memory_cached()<\/code><\/td><\/tr><tr><td><code>x.new_full()<\/code>, <code>new_zeros()<\/code>, <code>new_ones()<\/code>, <code>new_empty()<\/code>, <code>new_tensor()<\/code><\/td><td>Create a new tensor with the dtype and device of <code>x<\/code><\/td><td><code>torch.zeros_like(x)<\/code> and similar functions also keep the device<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> The cell commented &quot;Transferring a tensor from GPU 1 to GPU 0&quot; works only because the current device is 0 at that point. <code>x1.cuda()<\/code> copies to the current device. Inside <code>with torch.cuda.device(1):<\/code> the same call would return <code>x1<\/code> unchanged. Write <code>x1.to(&#039;cuda:0&#039;)<\/code> when you need a specific GPU.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Corrected and updated version of the lab<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The notebook was written for an older PyTorch release. The script below repeats its main steps with current APIs and explicit device indexes. It also skips the multi-GPU steps when only one GPU is present instead of failing.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import torch\n\n<span class=\"hljs-keyword\">if<\/span> not torch.cuda.is_available():\n    raise SystemExit(<span class=\"hljs-string\">\"No CUDA device visible to PyTorch\"<\/span>)\n\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"PyTorch\"<\/span>, torch.__version__, <span class=\"hljs-string\">\"| CUDA runtime\"<\/span>, torch.version.cuda)\nn = torch.cuda.device_count()\n<span class=\"hljs-keyword\">for<\/span> i in range(n):\n    <span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">\"cuda:{i} -&gt; {torch.cuda.get_device_name(i)}\"<\/span>)\n\ndev0 = torch.device(<span class=\"hljs-string\">\"cuda:0\"<\/span>)\nx = torch.tensor(&#91;<span class=\"hljs-number\">10.<\/span>, <span class=\"hljs-number\">20.<\/span>])          <span class=\"hljs-comment\"># CPU tensor<\/span>\nx0 = x.to(dev0)                       <span class=\"hljs-comment\"># explicit target device<\/span>\n\n<span class=\"hljs-comment\"># memory_cached() is deprecated: use memory_reserved()<\/span>\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"allocated:\"<\/span>, torch.cuda.memory_allocated(dev0))\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"reserved :\"<\/span>, torch.cuda.memory_reserved(dev0))\n\n<span class=\"hljs-comment\"># Mixing devices: move one operand first<\/span>\n<span class=\"hljs-keyword\">print<\/span>(x.to(x0.device) + x0)          <span class=\"hljs-comment\"># tensor(&#91;20., 40.], device='cuda:0')<\/span>\n\n<span class=\"hljs-keyword\">if<\/span> n &gt; <span class=\"hljs-number\">1<\/span>:\n    dev1 = torch.device(<span class=\"hljs-string\">\"cuda:1\"<\/span>)\n    x1 = x0.to(dev1)\n    <span class=\"hljs-keyword\">print<\/span>(x1 + x0.to(dev1))           <span class=\"hljs-comment\"># tensor(&#91;20., 40.], device='cuda:1')<\/span>\n    <span class=\"hljs-keyword\">print<\/span>(x1.new_zeros(<span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">2<\/span>).device)  <span class=\"hljs-comment\"># cuda:1<\/span>\n<span class=\"hljs-keyword\">else<\/span>:\n    <span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"Only one GPU: skipping cross-GPU steps\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><code>torch.cuda.memory_cached()<\/code> is replaced with <code>torch.cuda.memory_reserved()<\/code>. The old name was deprecated after the caching allocator&#039;s statistics were renamed.<\/li>\n\n\n<li>The failing additions <code>a + a0<\/code> and <code>a1 + a0<\/code> are fixed by moving one operand to the other&#039;s device first.<\/li>\n\n\n<li>In current releases the cross-device error message reads roughly <code>Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0!<\/code>. The <code>expected type torch.FloatTensor<\/code> and <code>binary_op()<\/code> messages in the notebook come from older versions.<\/li>\n\n\n<li>The device count is checked before <code>cuda:1<\/code> is used, so the script runs on one GPU as well as two.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Understanding GPU memory: allocated vs reserved<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">PyTorch does not return freed GPU memory to the driver straight away. Its caching allocator keeps freed blocks so later allocations can reuse them without calling the driver again. <code>memory_allocated()<\/code> counts bytes used by live tensors. <code>memory_reserved()<\/code> counts everything the allocator holds, including cached blocks that are currently empty. <code>nvidia-smi<\/code> shows a larger figure still, because it also includes the CUDA context and libraries such as cuBLAS and cuDNN.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>torch.cuda.empty_cache()<\/code> releases only cached blocks that no tensor is using. In the notebook the reserved figure stayed at 1048576 after <code>empty_cache()<\/code> because live tensors such as <code>x0<\/code>, <code>y<\/code> and <code>a0<\/code> were still stored in that block. The script below shows the full cycle:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import torch\ndev = torch.device(<span class=\"hljs-string\">\"cuda:0\"<\/span>)\nMiB = <span class=\"hljs-number\">2<\/span>**<span class=\"hljs-number\">20<\/span>\n\nt = torch.<span class=\"hljs-keyword\">empty<\/span>(<span class=\"hljs-number\">256<\/span>, <span class=\"hljs-number\">1024<\/span>, <span class=\"hljs-number\">1024<\/span>, device=dev)   <span class=\"hljs-comment\"># 1 GiB of float32<\/span>\n<span class=\"hljs-keyword\">print<\/span>(torch.cuda.memory_allocated(dev) <span class=\"hljs-comment\">\/\/ MiB, \"MiB allocated\")<\/span>\n\ndel t\n<span class=\"hljs-keyword\">print<\/span>(torch.cuda.memory_allocated(dev) <span class=\"hljs-comment\">\/\/ MiB, \"MiB allocated after del\")<\/span>\n<span class=\"hljs-keyword\">print<\/span>(torch.cuda.memory_reserved(dev) <span class=\"hljs-comment\">\/\/ MiB, \"MiB still reserved\")<\/span>\n\ntorch.cuda.empty_cache()\n<span class=\"hljs-keyword\">print<\/span>(torch.cuda.memory_reserved(dev) <span class=\"hljs-comment\">\/\/ MiB, \"MiB reserved after empty_cache\")<\/span>\n\n<span class=\"hljs-keyword\">print<\/span>(torch.cuda.max_memory_allocated(dev) <span class=\"hljs-comment\">\/\/ MiB, \"MiB peak\")<\/span>\n<span class=\"hljs-keyword\">print<\/span>(torch.cuda.memory_summary(dev, abbreviated=<span class=\"hljs-keyword\">True<\/span>))<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Expected result: about 1024 MiB allocated, 0 MiB allocated after <code>del<\/code>, about 1024 MiB still reserved, and close to 0 MiB reserved after <code>empty_cache()<\/code>. If anything else in the process is using that GPU, the numbers will be slightly higher.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> The memory functions report only the current device unless you pass a device. Tensors created on <code>cuda:1<\/code> in the notebook do not appear in the <code>memory_allocated()<\/code> figures, which were measured on device 0.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Device-agnostic and multi-GPU patterns<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Production code should pick a device once and pass it everywhere, rather than hard-coding <code>.cuda()<\/code>. That way the same script runs on a laptop CPU and on a GPU server:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import torch\n\ndevice = torch.device(<span class=\"hljs-string\">\"cuda\"<\/span> <span class=\"hljs-keyword\">if<\/span> torch.cuda.is_available() <span class=\"hljs-keyword\">else<\/span> <span class=\"hljs-string\">\"cpu\"<\/span>)\n\nmodel = torch.nn.Linear(<span class=\"hljs-number\">128<\/span>, <span class=\"hljs-number\">10<\/span>).to(device)       <span class=\"hljs-comment\"># moves parameters in place<\/span>\nbatch = torch.randn(<span class=\"hljs-number\">32<\/span>, <span class=\"hljs-number\">128<\/span>)\n\n<span class=\"hljs-comment\"># Pinned host memory + non_blocking lets the copy overlap with GPU work<\/span>\n<span class=\"hljs-keyword\">if<\/span> device.type == <span class=\"hljs-string\">\"cuda\"<\/span>:\n    batch = batch.pin_memory().to(device, non_blocking=<span class=\"hljs-keyword\">True<\/span>)\nout = model(batch)\n<span class=\"hljs-keyword\">print<\/span>(out.device)\n\n<span class=\"hljs-comment\"># Saving and loading across devices<\/span>\ntorch.save(model.state_dict(), <span class=\"hljs-string\">\"model.pt\"<\/span>)\nstate = torch.load(<span class=\"hljs-string\">\"model.pt\"<\/span>, map_location=device)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">To control which physical GPUs a process can see, set <code>CUDA_VISIBLE_DEVICES<\/code> before Python starts. Visible GPUs are numbered again from zero, so the command below runs on physical GPU 1, which the script sees as <code>cuda:0<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">CUDA_VISIBLE_DEVICES=<span class=\"hljs-number\">1<\/span> python train.py\nCUDA_VISIBLE_DEVICES=<span class=\"hljs-number\">0<\/span>,<span class=\"hljs-number\">2<\/span> python train.py   <span class=\"hljs-comment\"># two GPUs, seen as cuda:0 and cuda:1<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Because CUDA runs asynchronously, wall-clock timers around GPU code measure only how long it took to queue the work. Call <code>torch.cuda.synchronize()<\/code> before reading the timer, or use <code>torch.cuda.Event(enable_timing=True)<\/code> pairs, to measure actual GPU time.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Error<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>CUDA error: invalid device ordinal<\/code><\/td><td>The device index is not less than <code>device_count()<\/code>, as with <code>cuda:2<\/code> on a two-GPU machine<\/td><td>Check <code>torch.cuda.device_count()<\/code> and <code>CUDA_VISIBLE_DEVICES<\/code><\/td><\/tr><tr><td><code>Expected all tensors to be on the same device<\/code><\/td><td>An operation mixes CPU and GPU tensors, or two different GPUs<\/td><td>Move one operand with <code>.to(other.device)<\/code>. A 0-dimensional CPU tensor is allowed as a scalar operand<\/td><\/tr><tr><td><code>torch.cuda.is_available()<\/code> returns False<\/td><td>CPU-only PyTorch build, missing or too old driver, or GPUs hidden by <code>CUDA_VISIBLE_DEVICES<\/code><\/td><td>Check <code>torch.version.cuda<\/code> and <code>nvidia-smi<\/code>. Reinstall a CUDA build if needed<\/td><\/tr><tr><td><code>CUDA out of memory<\/code><\/td><td>Batch too large, or references kept alive, for example summing <code>loss<\/code> instead of <code>loss.item()<\/code><\/td><td>Reduce the batch size, use <code>torch.no_grad()<\/code> for inference, and release references. <code>empty_cache()<\/code> cannot free memory that live tensors are using<\/td><\/tr><tr><td><code>Cannot re-initialize CUDA in forked subprocess<\/code><\/td><td>CUDA was used before <code>multiprocessing<\/code> forked<\/td><td>Use the <code>spawn<\/code> start method, or initialise CUDA only in the child processes<\/td><\/tr><tr><td>Error reported on an unrelated line<\/td><td>Asynchronous kernel execution delays error reporting<\/td><td>Rerun with <code>CUDA_LAUNCH_BLOCKING=1<\/code> to get an accurate traceback<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Best practices<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Choose the device once and pass <code>device=<\/code> when creating tensors. This avoids creating a tensor on the CPU and then copying it.<\/li>\n\n\n<li>Prefer explicit <code>.to(&#039;cuda:N&#039;)<\/code> over relying on the current device, and keep <code>with torch.cuda.device()<\/code> blocks short.<\/li>\n\n\n<li>Use <code>new_*<\/code> and <code>*_like<\/code> functions inside library code so new tensors follow the device and dtype of their inputs.<\/li>\n\n\n<li>Keep host-device copies out of tight loops. Each <code>.item()<\/code>, <code>.cpu()<\/code> or <code>print(tensor)<\/code> makes the CPU wait for the GPU.<\/li>\n\n\n<li>Monitor <code>max_memory_allocated()<\/code> during training to size batches, and call <code>torch.cuda.reset_peak_memory_stats()<\/code> between experiments.<\/li>\n\n\n<li>For multi-GPU training, use <code>DistributedDataParallel<\/code> with one process per GPU rather than moving tensors between GPUs by hand.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What replaced torch.cuda.memory_cached()?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>torch.cuda.memory_reserved()<\/code> returns the same figure: the total bytes held by PyTorch&#039;s caching allocator. The old name is deprecated, so new code should use <code>memory_reserved()<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why does torch.cuda.empty_cache() not reduce memory usage?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It releases only cached blocks that no live tensor is using. Memory held by existing tensors, the CUDA context and libraries such as cuDNN stays allocated. To free tensor memory, delete the tensors first or let them go out of scope.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I run PyTorch on a specific GPU?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use an explicit device such as <code>torch.device(&#039;cuda:1&#039;)<\/code> with <code>.to()<\/code>, or start the process with <code>CUDA_VISIBLE_DEVICES=1<\/code>. The second option hides all other GPUs, and the chosen GPU appears as <code>cuda:0<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does tensor.cuda() copy the tensor every time?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. If the tensor is already on the target device, <code>.cuda()<\/code> and <code>.to()<\/code> return the original tensor without copying. Otherwise they return a new tensor on the target device.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I add a CPU tensor to a GPU tensor?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Not in general. PyTorch raises a same-device error unless the CPU tensor is 0-dimensional, which is treated as a scalar. Move one operand with <code>.to(other.device)<\/code> first.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/artificial-intelligence\/machine-learning\/\">More Machine Learning tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/staff-mlops-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/lead-machine-learning-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>This lab covers how PyTorch places tensors on GPUs: device objects, the current device, moving tensors between the CPU and GPUs, and how the CUDA caching allocator&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[6512],"tags":[7364],"class_list":["post-47567","post","type-post","status-publish","format-standard","hentry","category-machine-learning","tag-pytorch"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47567","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=47567"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47567\/revisions"}],"predecessor-version":[{"id":80168,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47567\/revisions\/80168"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=47567"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=47567"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=47567"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}