Repository navigation
Expand file tree
/
Copy pathdgl_model_sources.cpp
More file actions
310 lines (288 loc) · 14.9 KB
/
Copy pathdgl_model_sources.cpp
File metadata and controls
310 lines (288 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
#include "dgl_model_sources.h"
#include <algorithm>
#include <charconv>
#include <cstdlib>
#include <iterator>
#include <stdexcept>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif
#include "common.h"
namespace fs = std::filesystem;
void DGLModelSourceOptions::add_options(ArgOptions& options) {
options.manual_options.push_back({"", "--autodl", "on|off (default: off). Download missing DGL models",
[this](int argc, const char** argv, int index) {
const std::string_view value = index + 1 < argc ? argv[index + 1] : "";
if (value != "on" && value != "off") {
LOG_ERROR("--autodl requires on or off");
return -1;
}
autodl = value == "on";
return 1;
}});
options.manual_options.push_back({"", "--download-threads",
"maximum concurrent DGL transfers (default: " + std::to_string(sd::download::default_threads()) +
", range: 1-" + std::to_string(sd::download::max_threads) + ")",
[this](int argc, const char** argv, int index) {
const std::string_view value = index + 1 < argc ? argv[index + 1] : "";
int count = 0;
const auto end = value.data() + value.size();
const auto parsed = std::from_chars(value.data(), end, count);
if (parsed.ec != std::errc{} || parsed.ptr != end || count < 1 || count > sd::download::max_threads) {
LOG_ERROR("--download-threads requires a number from 1 to %d", sd::download::max_threads);
return -1;
}
threads = count;
return 1;
}});
options.manual_options.push_back({"", "--allow-download-dir", "allow downloads to this directory (repeatable)",
[this](int argc, const char** argv, int index) {
if (++index >= argc || !argv[index][0])
return -1;
dirs.push_back(argv_to_utf8(index, argv));
return 1;
}});
options.manual_options.push_back({"", "--allow-download-host", "allow HTTPS downloads from this hostname (repeatable)",
[this](int argc, const char** argv, int index) {
if (++index >= argc || !sd::download::valid_host(argv[index])) {
LOG_ERROR("--allow-download-host requires a hostname");
return -1;
}
hosts.push_back(sd::download::ascii_lowercase(argv[index]));
return 1;
}});
}
bool DGLModelSourceOptions::has_options() const {
return autodl.has_value() || threads.has_value() || !dirs.empty() || !hosts.empty();
}
static bool same_component(const fs::path& lhs, const fs::path& rhs) {
#ifdef _WIN32
return CompareStringOrdinal(lhs.c_str(), -1, rhs.c_str(), -1, TRUE) == CSTR_EQUAL;
#else
return lhs == rhs;
#endif
}
static bool inside(const fs::path& root, const fs::path& path) {
const auto [parent, child] = std::mismatch(root.begin(), root.end(), path.begin(), path.end(), same_component);
return parent == root.end() && child != path.end();
}
static fs::path canonical_download_root(const fs::path& path) {
auto root = fs::weakly_canonical(fs::absolute(path));
if (!root.has_filename() && root.has_relative_path())
root = root.parent_path();
const auto status = fs::status(root);
if (fs::exists(status) && !fs::is_directory(status))
throw std::runtime_error("download root is not a directory: " + path.u8string());
return root;
}
DGLModelSources::DGLModelSources(const DGLModelSourceOptions& options, std::vector<fs::path> model_roots)
: cwd_(fs::canonical(fs::current_path())), model_roots_(std::move(model_roots)), hosts_(options.hosts), threads_(options.threads.value_or(sd::download::default_threads())) {
write_roots_.push_back(cwd_);
for (const auto& dir : options.dirs)
write_roots_.push_back(canonical_download_root(cwd_ / fs::u8path(dir)));
}
static void check_model_host(std::string_view host, const std::vector<std::string>& extra) {
// https://huggingface.co/docs/hub/en/models-downloading#downloading-behind-a-proxy-or-firewall
constexpr std::string_view huggingface[] = {
"huggingface.co",
"cdn-lfs.huggingface.co",
"cdn-lfs.hf.co",
"cdn-lfs-us-1.hf.co",
"cdn-lfs-eu-1.hf.co",
"cas-bridge.xethub.hf.co",
"cas-server.xethub.hf.co",
"cas-server.xethub-eu.hf.co",
"transfer.xethub.hf.co",
"transfer.xethub-eu.hf.co",
"us.aws.cdn.hf.co",
"us.gcp.cdn.hf.co",
};
if (std::find(std::begin(huggingface), std::end(huggingface), host) == std::end(huggingface) &&
std::find(extra.begin(), extra.end(), host) == extra.end())
throw std::runtime_error("download hostname is not allowed: " + std::string(host) + " (use --allow-download-host)");
}
struct DGLModelSource {
std::string path;
std::string url;
std::string sha256;
size_t line = 0;
};
static constexpr std::string_view whitespace = " \t\r";
static std::string_view trim_source(std::string_view value) {
const auto first = value.find_first_not_of(whitespace);
if (first == std::string_view::npos)
return {};
return value.substr(first, value.find_last_not_of(whitespace) - first + 1);
}
static std::string source_location(size_t line) {
return "DGL model-source line " + std::to_string(line);
}
static std::runtime_error source_error(size_t line, const std::string& message) {
return std::runtime_error(source_location(line) + ": " + message);
}
static std::string parse_source_string(std::string_view& rest) {
if (rest.empty() || rest.front() != '"')
throw std::runtime_error("expected a double-quoted string");
size_t end = 1;
while (end < rest.size() && rest[end] != '"') {
if (rest[end++] == '\\' && end < rest.size())
++end;
}
if (end == rest.size())
throw std::runtime_error("unterminated string");
auto str = nlohmann::json::parse(rest.begin(), rest.begin() + end + 1, nullptr, false);
if (!str.is_string())
throw std::runtime_error("invalid string escape or UTF-8");
rest.remove_prefix(end + 1);
auto value = str.get<std::string>();
if (value.empty() || std::any_of(value.begin(), value.end(), [](unsigned char c) { return c < 32 || c == 127; }))
throw std::runtime_error("expected a nonempty string without control characters");
return value;
}
static DGLModelSource parse_model_source(std::string_view rest, size_t line) {
DGLModelSource entry;
entry.line = line;
while (true) {
const auto colon = rest.find(':');
if (colon == std::string_view::npos)
throw std::runtime_error("expected a key and ':'");
const auto key = trim_source(rest.substr(0, colon));
rest = trim_source(rest.substr(colon + 1));
if (key == "path" && entry.path.empty()) {
entry.path = parse_source_string(rest);
} else if (key == "url" && entry.url.empty()) {
entry.url = parse_source_string(rest);
} else if (key == "sha256" && entry.sha256.empty()) {
const auto end = rest.find(',');
entry.sha256 = sd::download::ascii_lowercase(trim_source(rest.substr(0, end)));
if (entry.sha256.size() != 64 || entry.sha256.find_first_not_of("0123456789abcdef") != std::string::npos)
throw std::runtime_error("sha256 must contain 64 hexadecimal digits");
rest = end == std::string_view::npos ? std::string_view{} : rest.substr(end);
} else {
throw std::runtime_error("unknown or repeated field");
}
rest = trim_source(rest);
if (rest.empty())
break;
if (rest.front() != ',')
throw std::runtime_error("expected ',' between fields");
rest.remove_prefix(1);
}
if (entry.path.empty() || entry.url.empty())
throw std::runtime_error("path and url are required");
return entry;
}
static std::vector<DGLModelSource> model_sources(std::string_view source) {
if (source.substr(0, 3) == "\xef\xbb\xbf")
source.remove_prefix(3);
constexpr std::string_view directive = "model-source:";
std::vector<DGLModelSource> entries;
size_t line_number = 0;
while (!source.empty()) {
++line_number;
const auto end = source.find('\n');
auto line = trim_source(source.substr(0, end));
source = end == std::string_view::npos ? std::string_view{} : source.substr(end + 1);
if (line.empty() || line.substr(0, 2) == "//")
continue;
if (line.front() != '#')
break;
line = trim_source(line.substr(1));
if (line.substr(0, directive.size()) != directive)
continue;
try {
entries.push_back(parse_model_source(line.substr(directive.size()), line_number));
} catch (const std::exception& error) {
throw source_error(line_number, error.what());
}
}
return entries;
}
static fs::path model_source_path(const fs::path& cwd, const std::string& value) {
auto path = fs::u8path(value);
#ifdef _WIN32
path.make_preferred();
if (path.native().compare(0, 4, L"\\\\?\\") == 0 || path.native().compare(0, 4, L"\\\\.\\") == 0 ||
(path.has_root_name() && !path.has_root_directory()))
throw std::runtime_error("invalid Windows model path");
for (const auto& part : path.relative_path()) {
const auto name = part.u8string();
if (name.empty() || name == "." || name == "..")
continue;
if (name.back() == ' ' || name.back() == '.' || name.find_first_of(":*?<>|\"") != std::string::npos)
throw std::runtime_error("invalid Windows model path component");
auto device = sd::download::ascii_lowercase(name.substr(0, name.find('.')));
device.erase(device.find_last_not_of(' ') + 1);
if (device == "con" || device == "prn" || device == "aux" || device == "nul" ||
device == "conin$" || device == "conout$" ||
((device.compare(0, 3, "com") == 0 || device.compare(0, 3, "lpt") == 0) &&
device.size() >= 4 && (device.substr(3) == "\xc2\xb9" || device.substr(3) == "\xc2\xb2" || device.substr(3) == "\xc2\xb3" || (device.size() == 4 && device.back() >= '0' && device.back() <= '9'))))
throw std::runtime_error("Windows device names cannot be model paths");
}
#endif
return cwd / path;
}
bool DGLModelSources::prepare(std::string_view source, const sd::download::Events& events) const {
struct Pending {
fs::path path;
const DGLModelSource* entry;
};
const auto entries = model_sources(source);
std::vector<Pending> pending;
for (const auto& entry : entries) {
if (events.cancelled && events.cancelled())
return false;
if (entry.sha256.empty())
continue;
try {
const auto path = model_source_path(cwd_, entry.path);
#ifdef _WIN32
// Checking an untrusted UNC path can contact its SMB server before any HTTPS request.
if (path.native().compare(0, 2, L"\\\\") == 0 &&
std::none_of(write_roots_.begin(), write_roots_.end(),
[&](const auto& root) { return inside(root, path.lexically_normal()); }))
throw std::runtime_error("UNC model path requires an explicitly allowed download directory");
#endif
if (fs::is_regular_file(fs::status(path)))
continue;
if (fs::symlink_status(path).type() != fs::file_type::not_found)
throw std::runtime_error("target is not a regular file: " + entry.path);
const auto target = fs::weakly_canonical(path);
if (std::any_of(target.begin(), target.end(), [](const auto& part) {
return sd::download::ascii_lowercase(part.u8string()) == sd::download::cache_directory;
}))
throw std::runtime_error("model target is inside the download cache: " + entry.path);
if (!model_roots_.empty() && std::none_of(model_roots_.begin(), model_roots_.end(),
[&](const auto& root) { return inside(root, target); }))
throw std::runtime_error("download target is outside the server model directories: " + entry.path);
if (std::none_of(write_roots_.begin(), write_roots_.end(), [&](const auto& root) { return inside(root, target); }))
throw std::runtime_error("download target is outside the allowed directories: " + entry.path +
" (use --allow-download-dir)");
auto previous = std::find_if(pending.begin(), pending.end(), [&](const auto& item) {
return same_component(item.path, target);
});
if (previous != pending.end()) {
if (previous->entry->url != entry.url || previous->entry->sha256 != entry.sha256)
throw std::runtime_error("conflicting declaration for " + entry.path +
" on line " + std::to_string(previous->entry->line));
continue;
}
pending.push_back({target, &entry});
} catch (const std::exception& error) {
throw source_error(entry.line, error.what());
}
}
std::vector<sd::download::Request> requests;
requests.reserve(pending.size());
for (const auto& item : pending) {
const auto& entry = *item.entry;
requests.push_back({item.path, entry.url, entry.sha256, source_location(entry.line) + ": " + entry.path});
}
const char* token = std::getenv("HF_TOKEN");
return sd::download::fetch(
requests, [&](std::string_view host) { check_model_host(host, hosts_); }, threads_, events,
{"huggingface.co", token ? token : ""});
}