sdcpp-model-load.js 13 KB

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