{"record":{"id":"c0c9a1086662521a","repo":"tracel-ai/burn","slug":"failed-to-read-tensor-data-synchronously-try-usin","errorCode":null,"errorMessage":"Failed to read tensor data synchronously. Try using nonzero_async instead.","messagePattern":"Failed to read tensor data synchronously\\. Try using nonzero_async instead\\.","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/burn-tensor/src/tensor/api/bool.rs","lineNumber":226,"sourceCode":"    /// the non-zero elements in that dimension.\n    ///\n    /// # Example\n    ///\n    /// ```rust\n    /// use burn_tensor::{Tensor, Bool};\n    ///\n    /// let device = Default::default();\n    /// let tensor = Tensor::<2, Bool>::from_bool(\n    ///     [[true, false, true], [false, true, false], [false, true, false]],\n    ///     &device,\n    /// );\n    /// let indices = tensor.nonzero();\n    /// println!(\"{}\", indices[0]); // [0, 0, 1, 2]\n    /// println!(\"{}\", indices[1]); // [0, 2, 1, 1]\n    /// ```\n    pub fn nonzero(self) -> Vec<Tensor<1, Int>> {\n        try_read_sync(self.nonzero_async())\n            .expect(\"Failed to read tensor data synchronously. Try using nonzero_async instead.\")\n    }\n\n    /// Compute the indices of `true` elements in the tensor (i.e., non-zero for boolean tensors).\n    ///\n    /// # Returns\n    ///\n    /// A vector of tensors, one for each dimension of the given tensor, containing the indices of\n    /// the non-zero elements in that dimension.\n    pub async fn nonzero_async(self) -> Vec<Tensor<1, Int>> {\n        let indices = self.argwhere_async().await;\n\n        if indices.shape().num_elements() == 0 {\n            // Return empty vec when all elements are zero\n            return vec![];\n        }\n\n        let dims = indices.shape();\n        indices","sourceCodeStart":208,"sourceCodeEnd":244,"githubUrl":"https://github.com/tracel-ai/burn/blob/d16f7ba2ed0d41408189384044cc886fb4c8f957/crates/burn-tensor/src/tensor/api/bool.rs#L208-L244","documentation":"Tensor::nonzero() synchronously reads the indices of true elements; on async backends (WGPU/CUDA) the result may not be ready or the backend may not support a blocking read, so try_read_sync returns None and the expect panics. The library offers nonzero_async() as the always-valid alternative.","triggerScenarios":"Calling `.nonzero()` on a tensor whose backend executes asynchronously and cannot synchronously resolve the future (e.g. WGPU in async runtime contexts, or inside an async function where block_on would deadlock).","commonSituations":"WGPU users calling nonzero() inside tokio tasks; batch verification code ported from CPU backends to GPU backends; sparse-mask extraction during inference on WebGPU.","solutions":["Switch to `tensor.nonzero_async()` and await it in an async context","Run the read on a CPU-capable step (e.g. `tensor.into_data()` / bring results back with an async read API)","Execute the call on a synchronous backend (NdArray/CPU) where sync reads are supported","Restructure code so the nonzero result is consumed asynchronously rather than blocking"],"exampleFix":"// before\nlet indices = tensor.nonzero();\n// after\nlet indices = tensor.nonzero_async().await;","handlingStrategy":"fallback","validationCode":"// prefer the async variant on GPU/async backends\nif backend_is_async() {\n    let indices = tensor.nonzero_async().await;\n}","typeGuard":null,"tryCatchPattern":"// expect() panics; avoid by using the async API\nlet indices = tokio::task::block_in_place(|| tensor.nonzero_async())\n    .map_err(|e| e)?;","preventionTips":["Use *_async variants whenever running on WGPU/CUDA backends","Avoid calling blocking tensor reads inside async runtimes","Use CPU backends (NdArray) when synchronous reads are required"],"tags":["async","sync-read","gpu","burn-tensor"],"backgroundTag":"blocking-async-read","analyzedSha":"d16f7ba2ed0d41408189384044cc886fb4c8f957","analyzedAt":"2026-09-05T13:19:14.260Z","contentChangedAt":"2026-09-05T13:19:14.260Z","schemaVersion":2},"datasetVersion":"2026-09-12T17:17:11.597Z"}