Efficient Way to Find Indices of Unique Rows in PyTorch Tensor

Abstract: Identifies indices of rows appearing exactly once in a PyTorch tensor using torch.unique without loops.

Created: 2026-08-04 by
To efficiently find the indices of unique rows in a PyTorch tensor, you can leverage torch.unique with the return_inverse or return_counts flags. By sorting the tensor along the first dimension and using these flags, you can map each row to its unique identifier and then filter for rows that appear exactly once. This approach avoids explicit Python loops, ensuring high performance on GPU devices while maintaining clarity in your data processing pipeline.

Understanding the Problem Context

In machine learning workflows, particularly when handling datasets with duplicates, identifying unique samples is crucial for model training integrity. You might encounter scenarios where a PyTorch tensor contains repeated rows representing identical data points. The goal is not just to remove duplicates but to know which original indices correspond to these unique entries. This information helps in debugging data pipelines or ensuring balanced sampling during training. Standard Python approaches using sets or dictionaries often fail because tensors are not hashable. Furthermore, converting tensors to NumPy arrays for processing can introduce significant overhead due to data transfer between CPU and GPU memory. Therefore, a pure PyTorch solution is preferred for its efficiency and compatibility with automatic differentiation graphs if needed.

Method 1: Using torch.unique with return_inverse

The most straightforward method involves using the torch.unique function. This function returns three values: the unique elements, their inverse indices, and optionally the counts of each element. To find unique rows, we treat each row as an element. First, ensure your tensor is contiguous. Non-contiguous tensors can cause issues with some operations. Then, apply torch.unique along dimension 0. If you need the indices of the first occurrence of each unique row, use the return_inverse=True flag. However, this gives you the mapping back to the unique set, not necessarily the count. To isolate strictly unique rows (those appearing only once), you should combine this with return_counts=True. Here is how you can implement this:
import torch

def get_unique_row_indices(tensor):
    # Ensure the tensor is contiguous for efficient processing
    tensor = tensor.contiguous()
    
    # Get unique rows, their inverse indices, and counts
    unique_rows, inverse_indices, counts = torch.unique(
        tensor, 
        dim=0, 
        sorted=True, 
        return_inverse=True, 
        return_counts=True
    )
    
    # Identify which unique rows appear exactly once
    is_unique = counts == 1
    
    # Map back to original indices
    # We need to find which original indices correspond to the unique rows
    # inverse_indices maps each original row to its position in unique_rows
    # We filter original indices where the corresponding unique row has count 1
    
    unique_mask = is_unique[inverse_indices]
    original_indices = torch.arange(tensor.size(0))
    
    return original_indices[unique_mask]
This code creates a boolean mask indicating which original rows belong to unique groups. It then filters the range of indices to return only those belonging to single-occurrence rows.

Method 2: Sorting and Grouping for Large Tensors

For very large tensors, torch.unique can be memory-intensive. An alternative approach involves sorting the tensor and then comparing adjacent rows. This method is more algorithmic but can be more memory-efficient. Sort the tensor based on its rows. Then, compare each row with its neighbor. If a row is different from both its predecessor and successor (handling edge cases), it is unique. This requires careful implementation to handle duplicates correctly.
def get_unique_indices_sort_method(tensor):
    # Sort the tensor and keep track of original indices
    sorted_tensor, sort_indices = torch.sort(tensor, dim=0)
    
    # Compare adjacent rows
    # Shift rows up and down
    prev_rows = torch.cat([sorted_tensor[:1], sorted_tensor[:-1]])
    next_rows = torch.cat([sorted_tensor[1:], sorted_tensor[-1:]])
    
    # Check if current row is different from previous and next
    diff_prev = (sorted_tensor != prev_rows).any(dim=1)
    diff_next = (sorted_tensor != next_rows).any(dim=1)
    
    # A row is unique if it differs from both neighbors
    is_unique = diff_prev & diff_next
    
    # Map back to original indices
    unique_sorted_indices = torch.where(is_unique)[0]
    original_indices = sort_indices[unique_sorted_indices]
    
    return original_indices
While this method avoids the overhead of computing full counts, it still requires sorting, which is O(N log N). For most practical purposes, Method 1 is more concise and leverages optimized C++ kernels within PyTorch.

Performance Considerations

When choosing between methods, consider the size of your tensor and available memory. torch.unique is highly optimized but may consume extra memory for intermediate tensors. If you are working on GPU, ensure that all operations remain on the same device to avoid costly transfers. Additionally, if your tensor contains floating-point numbers, be aware of precision issues. Two rows that are mathematically identical might differ by epsilon due to numerical errors. In such cases, consider rounding or using a tolerance-based comparison before applying uniqueness checks. For related insights on handling data shapes in PyTorch, you might find Understanding the Returned Shape of Targets in PyTorch Dataloader useful, as proper shape management often precedes advanced operations like this.

Frequently Asked Questions

What happens if my tensor has NaN values?

NaN values are treated as distinct from other values and from themselves in standard comparisons. torch.unique will typically group NaNs together. If you want to exclude NaN rows entirely, filter them out before applying the uniqueness check using torch.isnan() and logical indexing.

Can I use this method for 2D images instead of rows?

Yes, as long as you define "row" as a slice along a specific dimension. For images, you might flatten the spatial dimensions and treat each pixel vector as a row, though this is computationally expensive. It is better suited for tabular data or flattened feature vectors.

Is there a way to get unique columns instead of rows?

Simply transpose the tensor before applying the function. Use tensor.T or tensor.permute(1, 0) to swap axes, then apply the same logic. Remember to adjust the returned indices accordingly if you need them mapped back to the original column positions.

How does this handle duplicate unique rows?

If multiple rows are identical and appear more than once, they are not considered "unique" in the sense of having a count of one. The methods above specifically target rows that appear exactly once. If you want to keep one instance of every duplicate group, use return_inverse=True without the count filter.

Does this work with mixed data types?

No, PyTorch tensors require homogeneous data types. If your data includes strings or mixed types, you must convert them to a numeric representation first, such as encoding categories into integers. Once converted to a numeric tensor, the uniqueness check works seamlessly.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More