xref: /aosp_15_r20/external/pytorch/torch/csrc/api/include/torch/data/example.h (revision da0073e96a02ea20f0ac840b70461e3646d07c45)
1 #pragma once
2 
3 #include <torch/types.h>
4 
5 namespace torch {
6 namespace data {
7 
8 /// An `Example` from a dataset.
9 ///
10 /// A dataset consists of data and an associated target (label).
11 template <typename Data = at::Tensor, typename Target = at::Tensor>
12 struct Example {
13   using DataType = Data;
14   using TargetType = Target;
15 
16   Example() = default;
ExampleExample17   Example(Data data, Target target)
18       : data(std::move(data)), target(std::move(target)) {}
19 
20   Data data;
21   Target target;
22 };
23 
24 namespace example {
25 using NoTarget = void;
26 } // namespace example
27 
28 /// A specialization for `Example` that does not have a target.
29 ///
30 /// This class exists so that code can be written for a templated `Example`
31 /// type, and work both for labeled and unlabeled datasets.
32 template <typename Data>
33 struct Example<Data, example::NoTarget> {
34   using DataType = Data;
35   using TargetType = example::NoTarget;
36 
37   Example() = default;
38   /* implicit */ Example(Data data) : data(std::move(data)) {}
39 
40   // When a DataLoader returns an Example like this, that example should be
41   // implicitly convertible to the underlying data type.
42 
43   operator Data&() {
44     return data;
45   }
46   operator const Data&() const {
47     return data;
48   }
49 
50   Data data;
51 };
52 
53 using TensorExample = Example<at::Tensor, example::NoTarget>;
54 } // namespace data
55 } // namespace torch
56