sdcpp-model-load.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. /**
  2. * @node sdcpp-model-load
  3. * @name SD.cpp Load Model
  4. * @category sdcpp
  5. * @version 1.0.0
  6. * @description Make sure a model is loaded, without reloading one that already is
  7. * @icon box
  8. */
  9. // The credential this node wants, named so it can be found. It is stored as a
  10. // plain basic credential - that is what decides how it is encrypted - and this
  11. // only says which basic credential is the SD.cpp one. Anything that accepts a
  12. // basic credential still accepts this, and this node still accepts a plain
  13. // basic credential, because the shape is identical.
  14. const credentialTypes = [
  15. {
  16. id: 'sdcpp',
  17. label: 'SD.cpp Server',
  18. baseType: 'basic',
  19. description: 'The username and password you sign in to sdcpp-restapi with. The node exchanges them for a token before every call',
  20. usernameLabel: 'Username',
  21. passwordLabel: 'Password'
  22. }
  23. ];
  24. const configSchema = {
  25. type: 'object',
  26. // Pressing this asks the server what it has loaded and writes it into the
  27. // settings below - the model and every component it reports - so a workflow
  28. // can be built from a server that is already set up the way it should be,
  29. // rather than by typing the same names again.
  30. prefill: {
  31. label: 'Take from the server',
  32. description: 'Fill these in from the model the server currently has loaded',
  33. node: 'sdcpp-health',
  34. needs: ['serverUrl'],
  35. map: {
  36. modelName: 'modelName',
  37. modelType: 'modelType',
  38. 'loadedComponents.vae': 'vae',
  39. 'loadedComponents.clip_l': 'clipL',
  40. 'loadedComponents.clip_g': 'clipG',
  41. 'loadedComponents.t5xxl': 't5xxl',
  42. 'loadedComponents.llm': 'llm',
  43. 'loadedComponents.taesd': 'taesd',
  44. 'loadedComponents.controlnet': 'controlnet'
  45. }
  46. },
  47. properties: {
  48. serverUrl: {
  49. type: 'string', title: 'Server URL',
  50. description: 'Base address of the sdcpp-restapi server',
  51. default: 'http://localhost:8077'
  52. },
  53. credentialId: {
  54. type: 'string', title: 'Credential',
  55. description: 'A basic credential holding the sdcpp-restapi username and password',
  56. dynamicOptions: { source: 'credentials', filter: { type: ['sdcpp', 'basic'] } }
  57. },
  58. modelName: {
  59. type: 'string', title: 'Model',
  60. description: 'File name of the model, relative to its type directory. Browse lists what the server has of the Model Type chosen below',
  61. dynamicOptions: {
  62. source: 'node',
  63. node: 'sdcpp-model',
  64. config: { listOnly: true },
  65. itemsPath: 'models',
  66. valueKey: 'name',
  67. labelKey: 'name',
  68. needs: ['serverUrl', 'credentialId']
  69. }
  70. },
  71. modelType: {
  72. type: 'string', title: 'Model Type',
  73. enum: ['', 'checkpoint', 'diffusion'],
  74. default: '',
  75. description: 'checkpoint bundles U-Net, CLIP and VAE and suits SD1, SD2 and SDXL. diffusion holds only the U-Net or DiT and needs its components named separately, which is how Flux, SD3, Qwen, Wan and Z-Image load'
  76. },
  77. vae: {
  78. type: 'string', title: 'VAE',
  79. description: 'Component file name',
  80. dynamicOptions: {
  81. source: 'node',
  82. node: 'sdcpp-model',
  83. config: { listOnly: true, modelType: 'vae' },
  84. itemsPath: 'models',
  85. valueKey: 'name',
  86. labelKey: 'name',
  87. needs: ['serverUrl', 'credentialId']
  88. }
  89. },
  90. clipL: {
  91. type: 'string', title: 'CLIP-L',
  92. description: 'Component file name',
  93. dynamicOptions: {
  94. source: 'node',
  95. node: 'sdcpp-model',
  96. config: { listOnly: true, modelType: 'clip' },
  97. itemsPath: 'models',
  98. valueKey: 'name',
  99. labelKey: 'name',
  100. needs: ['serverUrl', 'credentialId']
  101. }
  102. },
  103. clipG: {
  104. type: 'string', title: 'CLIP-G',
  105. description: 'Component file name',
  106. dynamicOptions: {
  107. source: 'node',
  108. node: 'sdcpp-model',
  109. config: { listOnly: true, modelType: 'clip' },
  110. itemsPath: 'models',
  111. valueKey: 'name',
  112. labelKey: 'name',
  113. needs: ['serverUrl', 'credentialId']
  114. }
  115. },
  116. t5xxl: {
  117. type: 'string', title: 'T5-XXL',
  118. description: 'Component file name',
  119. dynamicOptions: {
  120. source: 'node',
  121. node: 'sdcpp-model',
  122. config: { listOnly: true, modelType: 't5' },
  123. itemsPath: 'models',
  124. valueKey: 'name',
  125. labelKey: 'name',
  126. needs: ['serverUrl', 'credentialId']
  127. }
  128. },
  129. llm: {
  130. type: 'string', title: 'LLM',
  131. description: 'Component file name, used by Z-Image, Qwen, Anima and Flux2',
  132. dynamicOptions: {
  133. source: 'node',
  134. node: 'sdcpp-model',
  135. config: { listOnly: true, modelType: 'llm' },
  136. itemsPath: 'models',
  137. valueKey: 'name',
  138. labelKey: 'name',
  139. needs: ['serverUrl', 'credentialId']
  140. }
  141. },
  142. taesd: {
  143. type: 'string', title: 'TAESD',
  144. description: 'Tiny autoencoder for progress previews',
  145. dynamicOptions: {
  146. source: 'node',
  147. node: 'sdcpp-model',
  148. config: { listOnly: true, modelType: 'taesd' },
  149. itemsPath: 'models',
  150. valueKey: 'name',
  151. labelKey: 'name',
  152. needs: ['serverUrl', 'credentialId']
  153. }
  154. },
  155. controlnet: {
  156. type: 'string', title: 'ControlNet',
  157. description: 'Component file name',
  158. dynamicOptions: {
  159. source: 'node',
  160. node: 'sdcpp-model',
  161. config: { listOnly: true, modelType: 'controlnet' },
  162. itemsPath: 'models',
  163. valueKey: 'name',
  164. labelKey: 'name',
  165. needs: ['serverUrl', 'credentialId']
  166. }
  167. },
  168. options: {
  169. type: 'object', title: 'Load Options',
  170. description: 'Extra load options passed through, such as flash_attn, enable_mmap, weight_type, stream_layers or max_vram'
  171. },
  172. whenDifferent: {
  173. type: 'string', title: 'When A Different Model Is Loaded',
  174. enum: ['load', 'fail'],
  175. default: 'load',
  176. description: 'load swaps it. fail stops the run instead - for a workflow that depends on a particular model already being in place and should not quietly spend minutes swapping it'
  177. },
  178. force: {
  179. type: 'boolean', title: 'Force Reload',
  180. default: false,
  181. description: 'Load again even when the right model is already loaded. Costs the full load time; useful after changing components or options, which this node cannot see from outside',
  182. showWhen: { field: 'whenDifferent', value: 'load' }
  183. },
  184. timeout: {
  185. type: 'number', title: 'Timeout (ms)',
  186. description: 'Loading reads gigabytes from disk and can take minutes',
  187. default: 300000
  188. }
  189. },
  190. required: []
  191. };
  192. const inputSchema = { type: 'object', properties: { data: { type: 'any' } } };
  193. const outputSchema = {
  194. type: 'object',
  195. properties: {
  196. modelName: { type: 'string', description: 'The model that is loaded now' },
  197. modelType: { type: 'string' },
  198. architecture: { type: 'string', description: 'Architecture the server detected, which decides generation defaults' },
  199. loaded: { type: 'boolean', description: 'True when this node performed a load' },
  200. alreadyLoaded: { type: 'boolean', description: 'True when the right model was already in place and nothing was done' },
  201. previousModel: { type: 'string', description: 'What was loaded before, when this node swapped it' },
  202. loadedComponents: { type: 'object' },
  203. elapsedMs: { type: 'number' }
  204. }
  205. };
  206. function normalizeServer(url) {
  207. const value = String(url || '').trim();
  208. if (!value) {
  209. throw new Error('SD.cpp: a server URL is required, such as http://localhost:8077');
  210. }
  211. return value.replace(/\/+$/, '');
  212. }
  213. function readCredential(credentialId) {
  214. const auth = smartbotic.credentials.get(credentialId);
  215. if (!auth || auth.success !== true) {
  216. throw new Error('SD.cpp: could not read the credential: ' +
  217. ((auth && auth.error) || 'unknown error'));
  218. }
  219. const value = auth.headerValue || '';
  220. if (value.indexOf('Basic ') !== 0) {
  221. throw new Error('SD.cpp: the credential must be a basic one, holding the sdcpp-restapi ' +
  222. 'username and password');
  223. }
  224. const decoded = smartbotic.utils.base64Decode(value.substring(6));
  225. const separator = decoded.indexOf(':');
  226. if (separator < 1) {
  227. throw new Error('SD.cpp: the credential is malformed, expected a username and a password');
  228. }
  229. return {
  230. username: decoded.substring(0, separator),
  231. password: decoded.substring(separator + 1)
  232. };
  233. }
  234. function call(options) {
  235. const response = smartbotic.http.request(options);
  236. let body = response.data;
  237. if (typeof body === 'string' && body.length > 0) {
  238. try {
  239. body = JSON.parse(body);
  240. } catch (e) {
  241. const snippet = body.substring(0, 200).replace(/\s+/g, ' ');
  242. throw new Error('SD.cpp: ' + options.what + ' returned HTTP ' + response.status +
  243. ' with a body that is not JSON: ' + snippet);
  244. }
  245. }
  246. if (response.status < 200 || response.status >= 300) {
  247. const detail = (body && (body.message || body.error)) || ('HTTP ' + response.status);
  248. throw new Error('SD.cpp: ' + options.what + ' failed: ' + detail);
  249. }
  250. return body || {};
  251. }
  252. function login(server, credential, timeout) {
  253. const session = call({
  254. method: 'POST',
  255. url: server + '/auth/login',
  256. headers: { 'Content-Type': 'application/json' },
  257. body: JSON.stringify({
  258. username: credential.username,
  259. password: credential.password
  260. }),
  261. timeout: timeout,
  262. what: 'signing in'
  263. });
  264. if (!session.token) {
  265. throw new Error('SD.cpp: the server accepted the login but returned no token');
  266. }
  267. return session.token;
  268. }
  269. // /health is unauthenticated, and it is the only way to find out what is
  270. // already loaded without asking for a token first.
  271. function readHealth(server, timeout) {
  272. return call({
  273. method: 'GET',
  274. url: server + '/health',
  275. timeout: timeout,
  276. what: 'reading server health'
  277. });
  278. }
  279. function putIfSet(target, key, value) {
  280. if (value === undefined || value === null || value === '') {
  281. return;
  282. }
  283. target[key] = value;
  284. }
  285. async function execute(config, input, context) {
  286. const server = normalizeServer(config.serverUrl);
  287. const timeout = config.timeout > 0 ? config.timeout : 300000;
  288. const modelName = String(config.modelName || '').trim();
  289. if (!modelName) {
  290. throw new Error('SD.cpp: a model name is required. Connect an SD.cpp Model node, ' +
  291. 'or type the file name');
  292. }
  293. // Ask what is loaded before loading anything. A load takes minutes and
  294. // unloads whatever was there, so doing it when the right model is already
  295. // resident is pure cost - and on a shared server it disrupts other work.
  296. const startedAt = Date.now();
  297. const health = readHealth(server, Math.min(timeout, 15000));
  298. const current = health.model_name || '';
  299. const sameModel = current === modelName;
  300. if (sameModel && config.force !== true) {
  301. smartbotic.log.info('SD.cpp: ' + modelName + ' is already loaded, nothing to do');
  302. return {
  303. modelName: current,
  304. modelType: health.model_type || '',
  305. architecture: health.model_architecture || '',
  306. loaded: false,
  307. alreadyLoaded: true,
  308. previousModel: '',
  309. loadedComponents: health.loaded_components || {},
  310. elapsedMs: Date.now() - startedAt
  311. };
  312. }
  313. if (!sameModel && (config.whenDifferent || 'load') === 'fail') {
  314. throw new Error('SD.cpp: this workflow expects "' + modelName + '" to be loaded, but ' +
  315. (current ? 'the server has "' + current + '"' : 'no model is loaded') +
  316. '. Set When A Different Model Is Loaded to "load" to swap it automatically');
  317. }
  318. const credential = readCredential(config.credentialId);
  319. const token = login(server, credential, Math.min(timeout, 30000));
  320. const body = { model_name: modelName };
  321. putIfSet(body, 'model_type', config.modelType);
  322. putIfSet(body, 'vae', config.vae);
  323. putIfSet(body, 'clip_l', config.clipL);
  324. putIfSet(body, 'clip_g', config.clipG);
  325. putIfSet(body, 't5xxl', config.t5xxl);
  326. putIfSet(body, 'llm', config.llm);
  327. putIfSet(body, 'taesd', config.taesd);
  328. putIfSet(body, 'controlnet', config.controlnet);
  329. if (config.options && typeof config.options === 'object') {
  330. body.options = config.options;
  331. }
  332. smartbotic.log.info('SD.cpp: loading ' + modelName +
  333. (current ? ' (replacing ' + current + ')' : ''));
  334. // Loading unloads whatever was in the slot first, and the server holds a
  335. // mutex for the duration, so this blocks until the weights are resident.
  336. const loaded = call({
  337. method: 'POST',
  338. url: server + '/models/load',
  339. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
  340. body: JSON.stringify(body),
  341. timeout: timeout,
  342. what: 'loading model ' + modelName
  343. });
  344. const after = readHealth(server, Math.min(timeout, 15000));
  345. return {
  346. modelName: loaded.model_name || modelName,
  347. modelType: loaded.model_type || config.modelType || '',
  348. architecture: after.model_architecture || '',
  349. loaded: true,
  350. alreadyLoaded: false,
  351. previousModel: sameModel ? '' : current,
  352. loadedComponents: loaded.loaded_components || after.loaded_components || {},
  353. elapsedMs: Date.now() - startedAt
  354. };
  355. }
  356. module.exports = { configSchema, inputSchema, outputSchema, execute };