blib/lib/PDL/IO/Safetensors.pm

filter: Statementstmt 100% 137 / 137 Branchbran 53.2% 33 / 62 Conditioncond 36.1% 17 / 47 MC/DCmcdc 0.0% 0 / 27 Subroutinesub 100% 13 / 13 Podpod 100% 3 / 3 totaltotal 70.2% 203 / 289 CC 53 SCAR 34.1
CC
53
Cov
76%
rsafetensors
54.3
wsafetensors
15.0
_read_header_fh
12.9
CRAP 30.3
↑ Summary
1 package PDL::IO::Safetensors;
2  
3 2 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use JSON::MaybeXS qw(encode_json decode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use PDL::Core ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use PDL::Lite ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use PDL::Types ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 2 our $VERSION = '0.012';
14 2 our @EXPORT_OK = qw(rsafetensors wsafetensors safetensors_header);
15  
16 2 my %DTYPE_TO_PDL = (
17 F64 => PDL::double(),
18 F32 => PDL::float(),
19 I64 => PDL::longlong(),
20 I32 => PDL::long(),
21 I16 => PDL::short(),
22 U8 => PDL::byte(),
23 I8 => PDL::sbyte(),
24 );
25  
26 2 my %PDL_TO_DTYPE = (
27 double => 'F64',
28 float => 'F32',
29 longlong => 'I64',
30 long => 'I32',
31 short => 'I16',
32 byte => 'U8',
33 sbyte => 'I8',
34 );
35  
36 2 my $MAX_HEADER_LEN = 100 * 1024 * 1024; # 100 MB per safetensors spec
37 2 my $MAX_SAFE_INT = 9_007_199_254_740_991; # 2^53 - 1
38  
39 3 ▶sub _read_header_fh {
Subroutine _read_header_fh: called CC=10 SCAR=25.5
40 3 my ($fh) = @_;
41 3 my $file_size = -s $fh;
42 3 ▶ croak 'Cannot determine safetensors file size' unless defined $file_size;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file_size 0 3 3
43 3 ▶ croak 'Truncated safetensors file' if $file_size < 8;
Branch: 1 branch
BranchTrueFalseTotal
if $file_size < 8 0 3 3
44  
45 3 my $len_buf;
46 3 my $n = read($fh, $len_buf, 8);
47 3 ▶ croak 'Truncated safetensors header length' unless defined $n && $n == 8;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == 8 0 3 3
Condition33%1/3
defined $n and $n == 8
!ll&&!rl&&r
003
MC/DC0%0/2
defined $n and $n == 8
defined $n $n == 8
Truth table33%1/3
A and B
A= defined $nB= $n == 8
ABresult
0X0
100
111
48 3 my $header_len = unpack('Q<', $len_buf);
49 3 ▶ croak "Safetensors header length $header_len exceeds 100 MB limit"
Branch: 1 branch
BranchTrueFalseTotal
if $header_len > $MAX_HEADER_LEN 0 3 3
50 if $header_len > $MAX_HEADER_LEN;
51 3 ▶ croak "Safetensors header length $header_len exceeds file size"
Branch: 1 branch
BranchTrueFalseTotal
if $header_len > $file_size - 8 0 3 3
52 if $header_len > $file_size - 8;
53  
54 3 my $json_buf;
55 3 $n = read($fh, $json_buf, $header_len);
56 3 ▶ croak 'Truncated safetensors JSON header' unless defined $n && $n == $header_len;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $header_len 0 3 3
Condition33%1/3
defined $n and $n == $header_len
!ll&&!rl&&r
003
MC/DC0%0/2
defined $n and $n == $header_len
defined $n $n == $header_len
Truth table33%1/3
A and B
A= defined $nB= $n == $header_len
ABresult
0X0
100
111
57 3 my $header = decode_json($json_buf);
58 2 ▶ croak 'Safetensors JSON header must be an object' unless ref($header) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $header eq "HASH" 0 2 2
59 2 return ($header, $header_len, $file_size);
60 }
61  
62 2 ▶sub safetensors_header {
Subroutine safetensors_header: called CC=3 SCAR=11.2
Pod documented
63 2 my ($file) = @_;
64 2 ▶ croak 'Filename required' unless defined $file;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file 0 2 2
65 2 ▶ open my $fh, '<:raw', $file or croak "Cannot open '$file': $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $file or croak("Cannot open '${file}': $!") 2 0 2
66 2 my ($header) = _read_header_fh($fh);
67 1 close $fh;
68 1 return $header;
69 }
70  
71 2 ▶sub rsafetensors {
Subroutine rsafetensors: called CC=30 SCAR=39.9
Pod documented
72 2 my ($file) = @_;
73 2 ▶ croak 'Filename required' unless defined $file;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file 0 2 2
74 2 ▶ open my $fh, '<:raw', $file or croak "Cannot open '$file': $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $file or croak("Cannot open '${file}': $!") 1 1 2
75 1 my ($header, $header_len, $file_size) = _read_header_fh($fh);
76  
77 1 my $data_start = 8 + $header_len;
78 1 my %tensors;
79  
80 1 for my $name (sort keys %{$header}) {
81 4 ▶ next if $name eq '__metadata__';
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "__metadata__" 1 3 4
82 3 my $info = $header->{$name};
83 3 ▶ croak "Invalid tensor metadata for '$name'" unless ref($info) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $info eq "HASH" 0 3 3
84 3 ▶ my $dtype = $info->{dtype} // croak "Missing dtype for '$name'";
Condition50%1/2
$info->{"dtype"} // croak("Missing dtype for '${name}'")
l!l
30
MC/DC0%0/1
$info->{"dtype"} // croak("Missing dtype for '${name}'")
$info->{"dtype"}
Truth table50%1/2
A
A= $info->{"dtype"}
Aresult
11
00
85 3 ▶ my $pdl_type = $DTYPE_TO_PDL{$dtype}
Condition50%1/2
$DTYPE_TO_PDL{$dtype} // croak("Unsupported safetensors dtype '${dtype}' for '${name}'")
l!l
30
MC/DC0%0/1
$DTYPE_TO_PDL{$dtype} // croak("Unsupported safetensors dtype '${dtype}' for '${name}'")
$DTYPE_TO_PDL{$dtype}
Truth table50%1/2
A
A= $DTYPE_TO_PDL{$dtype}
Aresult
11
00
86 // croak "Unsupported safetensors dtype '$dtype' for '$name'";
87 3 my $offsets = $info->{data_offsets};
88 croak "Invalid data_offsets for '$name'"
89 3 ▶ unless ref($offsets) eq 'ARRAY' && scalar(@{$offsets}) == 2;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $offsets eq "ARRAY" and scalar @{$offsets;} == 2 0 3 3
Condition33%1/3
ref $offsets eq "ARRAY" and scalar @{$offsets;} == 2
!ll&&!rl&&r
003
MC/DC0%0/2
ref $offsets eq "ARRAY" and scalar @{$offsets;} == 2
ref $offsets eq "ARRAY" scalar @{$offsets;} == 2
Truth table33%1/3
A and B
A= ref $offsets eq "ARRAY"B= scalar @{$offsets;} == 2
ABresult
0X0
100
111
90 3 my ($start, $end) = @{$offsets};
91 3 ▶ croak "Invalid data_offsets values for '$name'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $start and defined $end and $start =~ /\A\d+\z/ and $end =~ /\A\d+\z/ and $start <= $end 0 3 3
Condition33%4/12
defined $start and defined $end and $start =~ /\A\d+\z/ and $end =~ /\A\d+\z/ and $start <= $end
!ll&&!rl&&r
003
defined $start and defined $end and $start =~ /\A\d+\z/ and $end =~ /\A\d+\z/
!ll&&!rl&&r
003
defined $start and defined $end and $start =~ /\A\d+\z/
!ll&&!rl&&r
003
defined $start and defined $end
!ll&&!rl&&r
003
MC/DC0%0/5
defined $start and defined $end and $start =~ /\A\d+\z/ and $end =~ /\A\d+\z/ and $start <= $end
defined $start defined $end $start =~ /\A\d+\z/ $end =~ /\A\d+\z/ $start <= $end
Truth table16%1/6
A and B and C and D and E
A= defined $startB= defined $endC= $start =~ /\A\d+\z/D= $end =~ /\A\d+\z/E= $start <= $end
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
92 unless defined $start && defined $end
93 && $start =~ /\A\d+\z/ && $end =~ /\A\d+\z/
94 && $start <= $end;
95 3 ▶ croak "Tensor '$name' data_offsets exceed file size"
Branch: 1 branch
BranchTrueFalseTotal
if $end > $file_size - $data_start 0 3 3
96 if $end > $file_size - $data_start;
97 3 my $byte_len = $end - $start;
98  
99 3 ▶ my $raw_shape = $info->{shape} // [];
Condition50%1/2
$info->{"shape"} // []
l!l
30
MC/DC0%0/1
$info->{"shape"} // []
$info->{"shape"}
Truth table50%1/2
A
A= $info->{"shape"}
Aresult
11
00
100 3 ▶ croak "Invalid shape for '$name'" unless ref($raw_shape) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw_shape eq "ARRAY" 0 3 3
101 3 my $nelem = 1;
102 3 for my $d (@{$raw_shape}) {
103 4 ▶ croak "Invalid shape dimension for '$name'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $d and $d =~ /\A\d+\z/ 0 4 4
Condition33%1/3
defined $d and $d =~ /\A\d+\z/
!ll&&!rl&&r
004
MC/DC0%0/2
defined $d and $d =~ /\A\d+\z/
defined $d $d =~ /\A\d+\z/
Truth table33%1/3
A and B
A= defined $dB= $d =~ /\A\d+\z/
ABresult
0X0
100
111
104 unless defined $d && $d =~ /\A\d+\z/;
105 4 ▶ croak "Shape overflow for '$name'"
Branch: 1 branch
BranchTrueFalseTotal
if $d > 0 and $nelem > int $MAX_SAFE_INT / $d 0 4 4
Condition33%1/3
$d > 0 and $nelem > int $MAX_SAFE_INT / $d
!ll&&!rl&&r
040
MC/DC0%0/2
$d > 0 and $nelem > int $MAX_SAFE_INT / $d
$d > 0 $nelem > int $MAX_SAFE_INT / $d
Truth table33%1/3
A and B
A= $d > 0B= $nelem > int $MAX_SAFE_INT / $d
ABresult
0X0
100
111
106 if $d > 0 && $nelem > int($MAX_SAFE_INT / $d);
107 4 $nelem *= $d;
108 }
109 3 my $elem_bytes = PDL::Core::howbig($pdl_type);
110 3 ▶ croak "Byte size overflow for '$name'"
Branch: 1 branch
BranchTrueFalseTotal
if $nelem > int $MAX_SAFE_INT / $elem_bytes 0 3 3
111 if $nelem > int($MAX_SAFE_INT / $elem_bytes);
112 3 my $expected_bytes = $nelem * $elem_bytes;
113 3 ▶ croak "Tensor '$name' data_offsets length ($byte_len) != expected ($expected_bytes)"
Branch: 1 branch
BranchTrueFalseTotal
unless $byte_len == $expected_bytes 0 3 3
114 unless $byte_len == $expected_bytes;
115  
116 3 ▶ seek($fh, $data_start + $start, 0) or croak "seek failed: $!";
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, $data_start + $start, 0 or croak("seek failed: $!") 3 0 3
117 3 my $raw = '';
118 3 ▶ if ($byte_len > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($byte_len > 0) 3 0 3
119 3 my $got = read($fh, $raw, $byte_len);
120 3 ▶ croak "Truncated tensor data for '$name'" unless defined $got && $got == $byte_len;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $got and $got == $byte_len 0 3 3
Condition33%1/3
defined $got and $got == $byte_len
!ll&&!rl&&r
003
MC/DC0%0/2
defined $got and $got == $byte_len
defined $got $got == $byte_len
Truth table33%1/3
A and B
A= defined $gotB= $got == $byte_len
ABresult
0X0
100
111
121 }
122 3 ▶ croak "Payload length mismatch for '$name'" unless length($raw) == $expected_bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless length $raw == $expected_bytes 0 3 3
123  
124 3 my @shape = reverse @{$raw_shape};
125 3 my $pdl = PDL->zeroes($pdl_type, @shape);
126 3 ${ $pdl->get_dataref } = $raw;
127 3 $pdl->upd_data;
128 3 $tensors{$name} = $pdl;
129 }
130  
131 1 close $fh;
132 1 return \%tensors;
133 }
134  
135 1 ▶sub wsafetensors {
Subroutine wsafetensors: called CC=13 SCAR=27.1
Pod documented
136 1 my ($file, $tensors, $metadata) = @_;
137 1 ▶ croak 'Filename and tensor hashref required'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file and ref $tensors eq "HASH" 0 1 1
Condition33%1/3
defined $file and ref $tensors eq "HASH"
!ll&&!rl&&r
001
MC/DC0%0/2
defined $file and ref $tensors eq "HASH"
defined $file ref $tensors eq "HASH"
Truth table33%1/3
A and B
A= defined $fileB= ref $tensors eq "HASH"
ABresult
0X0
100
111
138 unless defined $file && ref($tensors) eq 'HASH';
139  
140 1 my %header;
141 1 ▶ if (ref($metadata) eq 'HASH' && %{$metadata}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $metadata eq "HASH" and %{$metadata;}) 1 0 1
Condition33%1/3
ref $metadata eq "HASH" and %{$metadata;}
!ll&&!rl&&r
001
MC/DC0%0/2
ref $metadata eq "HASH" and %{$metadata;}
ref $metadata eq "HASH" %{$metadata;}
Truth table33%1/3
A and B
A= ref $metadata eq "HASH"B= %{$metadata;}
ABresult
0X0
100
111
142 1 $header{'__metadata__'} = $metadata;
143 }
144  
145 1 my @chunks;
146 1 my $offset = 0;
147  
148 1 for my $name (sort keys %{$tensors}) {
149 3 my $pdl = $tensors->{$name};
150 croak "Value for '$name' is not a PDL ndarray"
151 3 ▶ unless ref($pdl) && eval { $pdl->isa('PDL') };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pdl and eval { do { $pdl->isa("PDL") } } 0 3 3
Condition33%1/3
ref $pdl and eval { do { $pdl->isa("PDL") } }
!ll&&!rl&&r
003
MC/DC0%0/2
ref $pdl and eval { do { $pdl->isa("PDL") } }
ref $pdl eval { do { $pdl->isa("PDL") } }
Truth table33%1/3
A and B
A= ref $pdlB= eval { do { $pdl->isa("PDL") } }
ABresult
0X0
100
111
152  
153 3 my $type_name = $pdl->type->ioname;
154 3 ▶ my $dtype = $PDL_TO_DTYPE{$type_name}
Condition50%1/2
$PDL_TO_DTYPE{$type_name} // croak("Unsupported PDL type '${type_name}' for '${name}'")
l!l
30
MC/DC0%0/1
$PDL_TO_DTYPE{$type_name} // croak("Unsupported PDL type '${type_name}' for '${name}'")
$PDL_TO_DTYPE{$type_name}
Truth table50%1/2
A
A= $PDL_TO_DTYPE{$type_name}
Aresult
11
00
155 // croak "Unsupported PDL type '$type_name' for '$name'";
156  
157 3 ▶ my $contig = $pdl->is_inplace ? $pdl : $pdl->make_physical;
Branch: 1 branch
BranchTrueFalseTotal
$pdl->is_inplace ? : 0 3 3
158 3 my $raw = ${ $contig->get_dataref };
159 3 my $len = length($raw);
160 3 my @shape = reverse $contig->dims;
161  
162 3 $header{$name} = {
163 dtype => $dtype,
164 shape => \@shape,
165 data_offsets => [ $offset, $offset + $len ],
166 };
167 3 push @chunks, $raw;
168 3 $offset += $len;
169 }
170  
171 1 my $json_bytes = encode_json(\%header);
172 1 ▶ open my $fh, '>:raw', $file or croak "Cannot write '$file': $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $file or croak("Cannot write '${file}': $!") 1 0 1
173 1 print {$fh} pack('Q<', length($json_bytes));
174 1 print {$fh} $json_bytes;
175 1 for my $chunk (@chunks) {
176 3 print {$fh} $chunk;
177 }
178 1 ▶ close $fh or croak "Failed closing '$file': $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("Failed closing '${file}': $!") 1 0 1
179 1 return 1;
180 }
181  
182 2 1;
183  
184 __END__
↑ Summary