-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(backend): Backend config convention and pull model #54
Merged
Merged
Changes from 7 commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
7635a8a
feat(backend): backend config convention
NarwhalChen c6fde4a
feat: adding pull model function with test
NarwhalChen 1deca3d
fix: adding default type
NarwhalChen e69b220
fix: fix the problem of prepare a unready config to other service
NarwhalChen 618c20e
fix: File naming is more semantic
NarwhalChen f1382eb
Merge remote-tracking branch 'origin/main' into backend-config-conven…
NarwhalChen 96a55d1
[autofix.ci] apply automated fixes
autofix-ci[bot] 71b662d
fix: fixing bug in modeldowloader that cannot pull model
NarwhalChen a4f692d
fix: fixing bug in modeldowloader that cannot pull model
NarwhalChen 458db40
Merge branch 'backend-config-convention' of https://github.com/Sma1lb…
NarwhalChen bf37046
[autofix.ci] apply automated fixes
autofix-ci[bot] 5a6f4bf
to: makes model download when project start and download to local folder
NarwhalChen ed2e534
to: can load model both locally and remotely
NarwhalChen 3ab6bc8
fix: fixing the layer structure of chatsconfig
NarwhalChen 3fe86b4
fix: fixing the layer structure of chatsconfig and relative bug in Lo…
NarwhalChen a2c07a6
[autofix.ci] apply automated fixes
autofix-ci[bot] f97b97d
fix: fixing the layer structure of chatsconfig and relative bug in Lo…
NarwhalChen eb55281
Merge branch 'backend-config-convention' of https://github.com/Sma1lb…
NarwhalChen 9c34f08
refactor: rename ConfigLoader and ModelLoader files, update imports, …
Sma1lboy ed07140
fix: updating layer structure of chatconfig and updating relative test
NarwhalChen 8a311f0
Delete .editorconfig
Sma1lboy 28d5f78
Delete pnpm-lock.yaml
Sma1lboy c1c8a98
Delete pnpm-lock.yaml
Sma1lboy 3ea4222
Merge branch 'main' into backend-config-convention
Sma1lboy 4e59695
Fix merge conflicts in pnpm-lock.yaml and update axios version to 1.7.8
Sma1lboy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
File renamed without changes.
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
import { ConfigLoader } from '../src/config/ConfigLoader'; | ||
import { ModelDownloader, getModel } from '../src/model/ModelDownloader'; | ||
|
||
const originalIsArray = Array.isArray; | ||
|
||
Array.isArray = jest.fn((type: any): type is any[] => { | ||
if ( | ||
type && | ||
type.constructor && | ||
(type.constructor.name === 'Float32Array' || | ||
type.constructor.name === 'BigInt64Array') | ||
) { | ||
return true; | ||
} | ||
return originalIsArray(type); | ||
}) as unknown as (arg: any) => arg is any[]; | ||
|
||
jest.mock('../src/config/ConfigLoader', () => { | ||
return { | ||
ConfigLoader: jest.fn().mockImplementation(() => { | ||
return { | ||
get: jest.fn().mockReturnValue({ | ||
chat1: { | ||
model: 'Xenova/LaMini-Flan-T5-783M', | ||
task: 'text2text-generation', | ||
}, | ||
}), | ||
validateConfig: jest.fn(), | ||
}; | ||
}), | ||
}; | ||
}); | ||
|
||
describe('loadAllChatsModels with real model loading', () => { | ||
beforeAll(async () => { | ||
await ModelDownloader.downloadAllModels(); | ||
}); | ||
|
||
it('should load real models specified in config', async () => { | ||
expect(ConfigLoader).toHaveBeenCalled(); | ||
|
||
const chat1Model = getModel('chat1'); | ||
expect(chat1Model).toBeDefined(); | ||
console.log('Loaded Model:', chat1Model); | ||
|
||
expect(chat1Model).toHaveProperty('model'); | ||
expect(chat1Model).toHaveProperty('tokenizer'); | ||
|
||
try { | ||
const chat1Output = await chat1Model( | ||
'Write me a love poem about cheese.', | ||
{ | ||
max_new_tokens: 200, | ||
temperature: 0.9, | ||
repetition_penalty: 2.0, | ||
no_repeat_ngram_size: 3, | ||
}, | ||
); | ||
|
||
console.log('Model Output:', chat1Output); | ||
expect(chat1Output).toBeDefined(); | ||
expect(chat1Output[0]).toHaveProperty('generated_text'); | ||
console.log(chat1Output[0].generated_text); | ||
} catch (error) { | ||
console.error('Error during model inference:', error); | ||
} | ||
}, 60000); | ||
}); | ||
|
||
afterAll(() => { | ||
Array.isArray = originalIsArray; | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import * as fs from 'fs'; | ||
import * as path from 'path'; | ||
import _ from 'lodash'; | ||
export interface ChatConfig { | ||
model: string; | ||
endpoint?: string; | ||
Sma1lboy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
token?: string; | ||
default?: boolean; | ||
task?: string; | ||
} | ||
export class ConfigLoader { | ||
private config: ChatConfig; | ||
|
||
private readonly configPath: string; | ||
|
||
constructor() { | ||
this.configPath = path.resolve(__dirname, 'config.json'); | ||
this.loadConfig(); | ||
} | ||
|
||
private loadConfig() { | ||
const file = fs.readFileSync(this.configPath, 'utf-8'); | ||
this.config = JSON.parse(file); | ||
} | ||
|
||
get<T>(path: string) { | ||
return _.get(this.config, path); | ||
} | ||
|
||
set(path: string, value: any) { | ||
_.set(this.config, path, value); | ||
this.saveConfig(); | ||
} | ||
|
||
private saveConfig() { | ||
fs.writeFileSync( | ||
this.configPath, | ||
JSON.stringify(this.config, null, 4), | ||
'utf-8', | ||
); | ||
} | ||
|
||
validateConfig() { | ||
if (!this.config) { | ||
throw new Error("Invalid configuration: 'chats' section is missing."); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import { Logger } from '@nestjs/common'; | ||
import { PipelineType, pipeline, env } from '@huggingface/transformers'; | ||
import { ConfigLoader, ChatConfig } from '../config/ConfigLoader'; | ||
|
||
type Progress = { loaded: number; total: number }; | ||
type ProgressCallback = (progress: Progress) => void; | ||
|
||
env.allowLocalModels = false; | ||
|
||
export class ModelDownloader { | ||
private static readonly logger = new Logger(ModelDownloader.name); | ||
private static readonly loadedModels = new Map<string, any>(); | ||
|
||
public static async downloadAllModels( | ||
Sma1lboy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
progressCallback: ProgressCallback = () => {}, | ||
): Promise<void> { | ||
const configLoader = new ConfigLoader(); | ||
configLoader.validateConfig(); | ||
const chats = configLoader.get<{ [key: string]: ChatConfig }>('chats'); | ||
|
||
const loadPromises = Object.entries(chats).map( | ||
async ([chatKey, chatConfig]: [string, ChatConfig]) => { | ||
const { model, task } = chatConfig; | ||
try { | ||
ModelDownloader.logger.log(`Starting to load model: ${model}`); | ||
const pipelineInstance = await ModelDownloader.downloadModel( | ||
task, | ||
model, | ||
progressCallback, | ||
); | ||
ModelDownloader.logger.log(`Model loaded successfully: ${model}`); | ||
this.loadedModels.set(chatKey, pipelineInstance); | ||
} catch (error) { | ||
ModelDownloader.logger.error( | ||
`Failed to load model ${model}:`, | ||
error.message, | ||
); | ||
} | ||
}, | ||
); | ||
|
||
await Promise.all(loadPromises); | ||
|
||
ModelDownloader.logger.log('All models loaded.'); | ||
} | ||
|
||
private static async downloadModel( | ||
task: string, | ||
model: string, | ||
progressCallback?: ProgressCallback, | ||
): Promise<any> { | ||
const pipelineOptions = progressCallback | ||
? { progress_callback: progressCallback } | ||
: undefined; | ||
return pipeline(task as PipelineType, model, pipelineOptions); | ||
} | ||
|
||
public static getModel(chatKey: string): any { | ||
return ModelDownloader.loadedModels.get(chatKey); | ||
} | ||
} | ||
|
||
export const getModel = ModelDownloader.getModel; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pin Hugging Face dependencies to specific versions
Using "latest" for production dependencies is risky as it can lead to unexpected breaking changes. Consider pinning to specific versions.